Bitcoinity.org

How I can write the for with fs::directory_iterator with parallel algortm

I have a function that works with 100% of the one core of CPU and now I'm trying to work with the parallel of an algorithm for move the work on the more core.
An example of my code without the parallel algorithm

template void SpyCBlock::convertData(T dao, const string &locationBitcoinCore, const string &destinationBitcoinCoreJson) { static_assert(std::is_base_of::value, "T must inherit from IDAOBlockchain"); int height = 0; string pathInput; bool isBitcoinDirectory = false; string fileExstension = exstensionFile(dao); while((pathInput = nameFileSearched(locationBitcoinCore)) != "") { try{ currentFile++; string fileNameOutput = getNameFile(pathInput); string pathOutput = destinationBitcoinCoreJson + fileNameOutput + fileExstension; dao.saveBlock(pathInput, pathOutput, height); isBitcoinDirectory = true; }catch(DAOException daoEx){ if(isBitcoinDirectory){ LOG(ERROR) << "The blk files are finished"; }else{ LOG(ERROR) << daoEx.what(); } } } } 
The core of the function is inside the method dao.saveBlock(pathInput, pathOutput, height);
I think this code can be moved with the multiprocessor and I'm learning on it, I know 2 libraries, on is OpenMP and I have raw in the C++17 the STL library for the parallel algorithms.

I have created my version parallel with the OpenMP library and the filesystem library with C++14, and I write this code I refactored the code with the code number 2
Code number 1
template void SpyCBlock::convertDataParallel(T dao, const string &locationBitcoinCore, const string &destinationBitcoinCoreJson) { static_assert(std::is_base_of::value, "T must inherit from IDAOBlockchain"); fs::path bitcoinBlockPath(locationBitcoinCore); std::string fileExstension = exstensionFile(dao); int height = -1; #pragma omp parallel { #pragma omp single { for(auto fileBlk : fs::directory_iterator(bitcoinBlockPath)) { std::string fileName = fileBlk.path().filename(); if(!fs::is_directory(fileBlk) && fileName.find("blk") != std::string::npos){ std::string pathFileOut = getNameFile(fileBlk.path().string()); #pragma omp task dao.saveBlock(fileBlk.path().string(), destinationBitcoinCoreJson + pathFileOut + fileExstension, height); } } } } } 
========| UPDATE |======
I have refactored the code multiprocessor with this code
code number 2
template void SpyCBlock::convertDataParallel(T &dao, const string &locationBitcoinCore, const string &destinationBitcoinCoreJson) { static_assert(std::is_base_of::value, "T must inherit from IDAOBlockchain"); if(locationBitcoinCore.empty() || destinationBitcoinCoreJson.empty()){ LOG(ERROR) << "The input argument are empty"; throw exception(); } //With execution parallel is not posssible set the real height of block, if I set the height = -1 the //dao insert inside the information of the link the hash block. LOG(ERROR) << "Location path " << locationBitcoinCore; fs::path bitcoinBlockPath(locationBitcoinCore); std::string fileExstension = exstensionFile(dao); int height = -1; int fileCount = 0; for(auto fileBlk : fs::directory_iterator(bitcoinBlockPath)) { std::string fileName = fileBlk.path().filename(); if(!fs::is_directory(fileBlk) && fileName.find("blk") != std::string::npos){ fileCount++; } } bool isBitcoinDirectory = false; #pragma omp parallel for for(int i = 0; i < fileCount; i++){ try{ string pathInput = nameFileSearched(locationBitcoinCore, i); LOG(INFO) << pathInput; string fileNameOutput = getNameFile(pathInput); string pathOutput = destinationBitcoinCoreJson + fileNameOutput + fileExstension; LOG(INFO) << pathOutput; if(compressionForm && !std::is_same::value){ dao.saveBlockCompress(pathInput, pathOutput, height); }else{ dao.saveBlock(pathInput, pathOutput, height); } isBitcoinDirectory = true; }catch(DAOException daoEx){ if(isBitcoinDirectory){ LOG(ERROR) << "The blk files are finished"; }else{ LOG(ERROR) << daoEx.what(); } //break; //If I introducing this I have introducing a condition on the value of block. //If i introducing the value break I don't have the possibility to read the value with irregular index } } } 

Now I'm asking if my code is better or is improvable or I'm wrong all.

also, with the C++17 and the STL parallel algorithm, my solution is better than the solution with OpenMP
submitted by crazyjoker96 to cpp_questions [link] [comments]

'Sophisticated' Hacker Plunders

'Sophisticated' Hacker Plunders $450,000 From Defi Protocol Balancer

Decentralized finance (Defi) protocol Balancer was on Sunday hacked for more than $450,000 worth of cryptocurrency.
In two separate transactions, an attacker targeted two pools containing Ethereum-based tokens with transfer fees – or so-called deflationary tokens.
Pools with Sta and Stonk tokens were affected by this exploit, Balancer, an automated market marker protocol, said on June 29.
The hacker made off with around 601 ether, 11 wrapped bitcoin (WBTC), 22,600 chainlink (LINK), and 61,000 synthetix (SNX) – altogether totaling more than $451,000.
According to an analysis by Dex aggregator 1inch.exchange, the attacker used a smart contract to automate multiple actions in a single transaction. First, the hacker obtained a flash loan of $23 million worth of ethereum from the crypto-lending platform Dydx.
The money was used to swap Weth to Statera (Sta), a so-called deflationary token, back and forth 24 times until the Sta balance was totally drained. With Sta, at least one percent of the token is programmed to burn with every transaction.
However, the Balancer pool apparently failed to account for this mechanism. So, the Sta balance declined by one percent every time the attacker made their 24 swaps. After this, the hacker exchanged 1 weiSta, or the equivalent of a billionth of a token, to Weth several times.
Due to Sta token transfer fee implementation, the pool never received statera, but still proceeded to release the wrapped ether regardless, said 1inch. The same step was repeated to drain WBTC, SNX, and link token balances from the pool, it added.
Finally, the attacker repaid the $23 million Dydx loan. Later, they converted the Sta tokens to Balancer pool tokens and eventually into ethereum via Uniswap, which was then cashed out.
1inch noted that the attack was carried out by a “sophisticated smart contract engineer” who is deeply knowledgeable about decentralized finance and its protocols.
Balancer claimed that “we were not aware this specific type of attack was possible, [but] we have consistently…warned about the unintended effects ERC20s with transfer fees could have in the protocol.”
To prevent future attacks, the platform said that it will start to add ‘transfer fee tokens to the UI blacklist similarly to what we have done for no bool transfer tokens.”
“We will be adding more documentation around the risks of how these pools work and how broken or maliciously designed tokens can potentially drain assets from a pool,” it added.
A number of Defi platforms have been hacked this year. In February, Bzx protocol was attacked twice while Maker lost around $8.3 million in March. Uniswap and Dforce were drained of $300,000 and $25 million, respectively, although this later amount was returned by the hacker in April.
What do you think about the Balancer pool hack? Let us know in the comments section below.
submitted by TatoxExchange to u/TatoxExchange [link] [comments]

Contrats d'exécution consensuels de VDS et processus du téléchargement à la chaîne

Résumé des contrats d’exécution consensuels
Le concept de base du contrat d’exécution consensuels
Contrats d’exécution consensuels, connu sous le nom de contrat intelligent dans l'industrie de la blockchain, mais l'équipe de VDS estime que ce terme est trop marketing, car nous n'avons pas trouvé à quel point la technologie de programmation contractuelle est intelligente jusqu'à présent, il s'agit simplement d'un système décentralisé dans le réseau distribué, la procédure prédéfinie de comportement consensuel formée par l'édition de code. Dans l'esprit de rechercher la vérité à partir des faits, nous pensons qu'il est plus approprié de renommer le contrat intelligent en tant que contrat d'exécution de consensus. Lorsque les humains combineront la technologie blockchain avec la technologie d'intelligence artificielle de AI à l'avenir, les obstacles à la compréhension des noms sont éliminés.
Le contrat d'exécution consensuel peut être appliqué à de nombreuses industries, telles que la finance, l'éducation, les systèmes administratifs, l'Internet des objets, le divertissement en ligne, etc. Grâce à la technologie de la blockchain, dans un réseau distribué spécifique, un script d'exécution qui est formé par l'édition de pré-code sans aucune intervention de tiers et le comportement de consensus des deux parties ou de plusieurs parties impliquées dans le protocole. Il garantit l’exécution sûre, stable et équitable des droits et intérêts de tous les participants au contrat.
Le contrat d'exécution consensuel a joué un rôle dans l'accélération de l'atterrissage de diverses applications pour le développement de l'industrie de la blockchain et a incité davantage de développeurs à y participer activement, révolutionnant l'expérience réelle des produits de la technologie de la blockchain. Tout découle des contributions exceptionnelles de l'équipe Ethereum, ouvrant une nouvelle porte à l'ensemble de l'industrie.
Structure de base et jonction
L’intégration de EVM
La machine virtuelle Ethereum (EVM) utilise un code machine 256 bits et est une machine virtuelle basée sur la pile utilisée pour exécuter les contrats d'exécution consensuels d'Ethereum. Étant donné que l'EVM est conçu pour le système Ethereum, le modèle de compte Ethereum (Account Model) est utilisé pour la transmission de valeurs. La conception de la chaîne VDS est basée sur le modèle Bitcoin UTXO. La raison de cette conception est, d'une part, c'est en raison de la nécessité de réaliser la fonction d'échange de résonance de VDS et la fonction d'échange inter-chaîne unidirectionnelle de bitcoin à chaîne VDS, qui peuvent réaliser la génération de deux adresses différentes de bitcoin et VDS avec une clé privée. D'autre part, l'équipe VDS estime que la structure sous-jacente des transactions Bitcoin est plus stable et fiable grâce à 10 ans de pratique sociale. Par conséquent, VDS utilise une couche d'abstraction de compte (Account Abstraction Layer) pour convertir le modèle UTXO en un modèle de compte qui peut être exécuté par EVM. De plus, VDS a ajouté une interface basée sur le modèle de compte, afin qu'EVM puisse lire directement les informations sur la chaîne VDS. Il convient de noter que la couche d'abstraction de compte peut masquer les détails de déploiement de certaines fonctions spécifiques et établir une division des préoccupations pour améliorer l'interopérabilité et l'indépendance de la plate-forme.
Dans le système Bitcoin, ce n'est qu'après la vérification du script de déverrouillage (Script Sig) et du script de verrouillage (Script Pub Key) que la sortie de transaction correspondante peut être dépensée.
Par exemple, le script de verrouillage verrouille généralement une sortie de transaction sur une adresse bitcoin (la valeur de hachage de la clé publique). Ce n'est que lorsque les conditions de configuration du script de déverrouillage et du script de verrouillage correspondent, que l'exécution du script combiné affiche le résultat sous la forme True (la valeur de retour de système est 1), de sorte que la sortie de transaction correspondante sera dépensée.
Dans le système distribué de VDS, nous soulignons l'opportunité de l'exécution du contrat d'exécution consensuel. Par conséquent, nous avons ajouté les opérateurs OP_CREATE et OP_CALL au script de verrouillage. Lorsque le système de VDS détecte cet opérateur, les nœuds de l'ensemble du réseau exécuteront la transaction. De cette façon, le rôle joué par le script Bitcoin est plus de transférer les données pertinentes vers EVM, pas seulement en tant que langage de codage. Tout comme Ethereum exécute un contrat d'exécution de consensus, le contrat déclenché par les opérateurs OP_CREATE et OP_CALL, EVM changera son état dans sa propre base de données d'état.
Compte tenu de la facilité d'utilisation du contrat d'exécution du consensus de la chaîne VDS, il est nécessaire de vérifier les données qui déclenchent le contrat et la valeur de hachage de la clé publique de la source de données.
Afin d'éviter que la proportion d'UTXO sur la chaîne de VDS ne soit trop importante, la sortie de transaction de OP_CREATE et OP_CALL est t conçue pour être dépensée. La sortie de OP_CALL peut envoyer des fonds pour d'autres contrats ou adresses de hachage de clé publique.
Tout d’abord, pour le contrat d'exécution consensuel créé sur la chaîne VDS, le système généreraune valeur de hachage de transaction pour l'appel de contrat.Le contrat nouvellement libéré a un solde initial de 0 (les contrats avec un solde initial ne sont pas 0 ne sont pas pris en charge). Afin de répondre aux besoins du contrat d'envoi de fonds, VDS utilise l'opérateur OP_CALL pour créer une sortie de transaction. Le script de sortie du contrat d'envoi de fonds est similaire à :
1: the version of the VM
10000: gas limit for the transaction
100: gas price in Qtum satoshis
0xF012: data to send to the contract (usually using the solidity ABI)
0x1452b22265803b201ac1f8bb25840cb70afe3303:
ripemd-160 hash of the contract txid OP_CALL
Ce script n'est pas compliqué et OP_CALL effectue la plupart du travail requis. VDS définit le coût spécifique de la transaction (sans tenir compte de la situation de out-of-gas) comme Output Value, qui est Gas Limit. Le mécanisme spécifique du Gas sera discuté dans les chapitres suivants. Lorsque le script de sortie ci-dessus est ajouté à la blockchain, la sortie établit une relation correspondante avec le compte du contrat et se reflète dans le solde du contrat. Le solde peut être compris comme la somme des coûts contractuels disponibles.
La sortie d'adresse de hachage de clé publique standard est utilisée pour le processus de base des transactions de contrat, et le processus de transaction entre les contrats est également généralement cohérent. En outre, vous pouvez effectuer des transactions par P2SH et des transactions non standard (non-standard transactions). Lorsque le contrat actuel doit être échangé avec un autre contrat ou une adresse de hachage de clé publique, la sortie disponible dans le compte du contrat sera consommée. Cette partie de la sortie consommée doit être présente pour la vérification des transactions dans le réseau de VDS, que nous appelons la transaction attendue du contrat (Expected Contract Transactions). Étant donné que la transaction attendue du contrat est générée lorsque le mineur vérifie et exécute la transaction, plutôt que d'être générée par l'utilisateur de la transaction, elle ne sera pas diffusée sur l'ensemble du réseau.
Le principe de fonctionnement principal de la transaction attendue du contrat est réalisé par le code OP_SPEND. OP_CREATE et OP_CALL ont deux modes de fonctionnement. Lorsque l'opérateur est utilisé comme script de sortie, EVM l'exécute, lorsque l'opérateur est utilisé comme script d'entrée, EVM ne sera pas exécuté (sinon il provoquera une exécution répétée). Dans ce cas, OP_CREATE et OP_CALL peuvent être utilisés comme Opération sans commandement. OP_CREATE et OP_CALL reçoivent la valeur de hachage de transaction transmise par OP_SPEND et renvoient 1 ou 0 (c'est-à-dire il peut être dépensé ou pas). Il montre l'importance de OP_SPEND dans la transaction attendue de l'intégralité du contrat. Plus précisément, lorsque OP_SPEND transmet la valeur de hachage de transaction à OP_CREATE et OP_CALL, OP_CREATE et OP_CALL comparent si la valeur de hachage existe dans la liste des transactions attendues du contrat. S'il existe, renvoyez 1 pour dépenser, sinon retournez 0, ce n'est pas pour dépenser. Cette logique fournit indirectement un moyen complet et sûr de garantir que les fonds du contrat ne peuvent être utilisés que par le contrat, ce qui est cohérent avec le résultat des transactions UTXO ordinaires.
Lorsque le contrat EVM envoie des fonds à l'adresse de hachage de clé publique ou à un autre contrat, une nouvelle transaction sera établie. À l'aide de l'algorithme de Consensus-critical coin picking, la sortie de transaction la plus appropriée peut être sélectionnée dans le pool de sortie disponible du contrat. La sortie de transaction sélectionnée sera utilisée comme script d'entrée pour exécuter un seul OP_SPEND, et la sortie est l'adresse cible des fonds, et les fonds restants seront renvoyés au contrat, tout en modifiant la sortie disponible pour la consommation. Ensuite, la valeur de hachage de cette transaction sera ajoutée à la liste des transactions attendues du contrat. Lorsque la transaction est exécutée, la transaction sera immédiatement ajoutée au bloc. Une fois que les mineurs de la chaîne ont vérifié et exécuté la transaction, la liste des transactions attendues du contrat est à nouveau parcourue. Une fois la vérification correcte, la valeur de hachage est supprimée de la table. De cette façon, l'utilisation de OP_SPEND peut effectivement empêcher l'utilisation de valeurs de hachage codées en dur pour modifier le coût de la sortie.
La couche d'abstraction des comptes VDS élimine la nécessité pour l'EVM d'accorder trop d'attention à coin-picking. Il lui suffit de connaître le solde du contrat et peut échanger des fonds avec d'autres contrats ou même des adresses de hachage de clé publique. De cette façon, seule une légère modification du contrat d'exécution du consensus Ethereum peut répondre aux exigences de fonctionnement du contrat VDS.
En d'autres termes, tant que le contrat d'exécution consensuel peut être exécuté sur la chaîne Ethereum, il peut s'exécuter sur la chaîne VDS.
Achèvement de AAL
La conception de la chaîne VDS est basée sur le modèle Bitcoin UTXO. La plate-forme générale de contrat d'exécution de consensus utilise le modèle de compte. Étant donné que le contrat en tant qu'entité nécessite un logo de réseau, ce logoest l'adresse du contrat, de sorte que le fonctionnement et la gestion du contrat d'exécution consensuel peuvent être effectués par cette adresse. La couche d'abstraction de compte est ajoutée à la conception du modèle (Account Abstraction Layer, AAL) de chaîne de VDS, qui est utilisée pour convertir le modèle UTXO en un modèle de compte qui peut être exécuté par le contrat.
Pour les développeurs qui exécutent des contrats par consensus, le modèle de compte de la machine virtuelle est relativement simple. Il prend en charge l'interrogation des soldes des contrats et peut également envoyer des fonds pour d'autres contrats. Bien que ces opérations semblent très simples et basiques, toutes les transactions de la chaîne VDS utilisent le langage de script Bitcoin, et il est plus compliqué que prévu d'être implémenté dans la couche d'abstraction de compte de la chaîne VDS basée sur le modèle Bitcoin UTXO. AAL a donc élargi sa base en ajoutant trois nouveaux opérateurs :
OP_CREATE est utilisé pour effectuer la création de contrats intelligents, transmettre le code d'octet transmis via la transaction à la base de données de stockage de contrats de la machine virtuelle et générer un compte de contrat.
OP_CALL est utilisé pour transférer les données pertinentes et les informations d'adresse nécessaires pour appeler le contrat et exécuter le contenu du code dans le contrat. (Cet opérateur peut également envoyer des fonds pour des contrats d'exécution consensuels).
OP_SPEND utilise la valeur de hachage de ID de contrat actuel comme transaction d'entrée HASH ou transaction HASH envoyée à l'UTXO du contrat, puis utilise OP_SPEND comme instruction de dépense pour créer un script de transaction.
Utilisation des Contrats et processus du téléchargement à la chaîne
Rédiger les contrats
Il est actuellement possible d'utiliser le langage Solidity pour rédiger des contrats d'exécution de consensus.
Utilisez Solidity Remix ou un autre Solidity IDE pour l'écriture et la compilation de code.
solidity remix(https://remix.ethereum.org/
Il est recommandé d'utiliser le mode homestead pour compiler.
Il est recommandé d'utiliser la version solidité 0.4.24 (si d'autres versions sont utilisées, cela peut provoquer des erreurs ou des échecs).
La syntaxe Solidity peut être référencée(https://solidity.readthedocs.io/en)
Compiler et déployer les contrats
Fonctionnement du contrat intelligent de vdsd
Examiner les variables de fonctionnement de l'environnement
vdsd -txindex=1 -logevents=1 -record-log-opcodes=1 -regtest=1
> Les tests sous contrat sont effectués dans l'environnement de test. Il est recommandé de tester après avoir atteint une hauteur de 440 blocs.
440 blocs hautement achevés l'opération de retour de fonds après les événements anormaux du contrat (refund) et (revert).
La commande de contrat de déploiement est :
```vds-cli deploycontract bytecode ABI parameters```
- bytecode (string, required) contract bytecode.
- ABI (string, required) ABI String must be JSON formatted.
- parameters (string, required) a JSON array of parameters.
Cette fonction est utilisée pour l'exécution du constructeur du contrat avec les paramètres entrants pour obtenir le ByteCode qui est finalement utilisé pour le déploiement.
(Cette méthode consiste à associer le bytecode à ABI et à le stocker localement pour l'enregistrement. Il peut appeler des méthodes internes localement et renvoyer le bytecode approprié)
```vds-cli createcontract bytecode (gaslimit gasprice senderaddress broadcast)```
- bytecode (string, required) contract bytecode.
- gaslimit (numeric or string, optional) gasLimit, default is DEFAULT_GAS_LIMIT, recommended value is 250000.
- gasprice (numeric or string, optional) gasprice, default is DEFAULT_GAS_PRICE, recommended value is 0.00000040.
- senderaddress (string, optional) The vds address that will be used to create the contract.
- broadcast (bool, optional, default=true) Whether to broadcast the transaction or not.
- changeToSender (bool, optional, default=true) Return the change to the sender.
La valeur de retour est : txid, éxpéditeur, hachage de l'expéditeur160, adresse du contrat
Consulter si la commande a été exécutée avec succès :
```vds-cli gettransactionreceipt txid```
La valeur de retour de txid pour les transactions non contractuelles est vide
La valeur de retour est : Les informations pertinentes de txid sur la BlockHash Hachage du bloc
- blockNumber Hauteur de bloc
- transactionHash Hachage de transaction
- transactionIndex La position de l'échange dans le bloc
- from Hachage de l’adresse de l’expéditeur 160
- to Le destinataire est l'adresse du contrat, le lieu de création de la transaction contractuelle est 00000000000000000000000000000
- cumulativeGasUsed Gas accumulé
- gasUsed Gaz réellement utilisé
- contractAddress Adresse du contrat
- excepted Y a-t-il des erreurs
- exceptedMessage Message d'erreur
-
Il convient de noter que le champ excepted n'est pas None, ce qui indique que l'exécution du contrat a échoué. Bien que la transaction puisse être vérifiée sur la chaîne, cela ne signifie pas que le contrat a été exécuté avec succès, c'est-à-dire que les frais de traitement pour l'exécution de ce contrat ne sont pas remboursables. Les frais de traitement ne seront remboursés que si la méthode revert est entrée dans le contrat, et les frais de méthode ne seront pas remboursés pour la méthode assert.
Appel des contrats
```vds-cli addcontract name contractaddress ABI decription```
- name (string required) contract name.
- contractaddress (string required) contract address.
- ABI (string, required) ABI String must be JSON formatted.
- description (string, optional) The description to this contract.
Cette fonction est utilisée pour ajouter le contrat ABI à la base de données locale.
```vds-cli getcontractinfo contractaddress```
- contractaddress (string required) contract address.
Cette fonction est utilisée pour obtenir les informations du contrat ajouté.
```vds-cli callcontractfunc contractaddress function parameters```
- contractaddress (string, required) The contract address that will receive the funds and data.
- function (string, required) The contract function.
- parameters (string, required) a JSON array of parameters.
Cette fonction renverra le résultat de l'exécution lors de l'appel de la méthode constante ordinaire, comme l'appel de la méthode d'opération de données de contrat retournera la chaîne de format hexadécimal du script d'opération.
```vds-cli sendtocontract contractaddress data (amount gaslimit gasprice senderaddress broadcast)```
- contractaddress (string, required) The contract address that will receive the funds and data.
- datahex (string, required) data to send.
- amount (numeric or string, optional) The amount in " + CURRENCY_UNIT + " to send. eg 0.1, default: 0
- gaslimit (numeric or string, optional) gasLimit, default is DEFAULT_GAS_LIMIT, recommended value is 250000.
- gasprice (numeric or string, optional) gasprice, default is DEFAULT_GAS_PRICE, recommended value is 0.00000040.
- senderaddress (string, optional) The vds address that will be used to create the contract.
- broadcast (bool, optional, default=true) Whether to broadcast the transaction or not.
- changeToSender (bool, optional, default=true) Return the change to the sender.
Cette fonction est utilisée pour envoyer le script d'opération de contrat au contrat spécifié et le faire enregistrer sur la blockchain.
Consultation des résultats d’exécution des contrats
```vds-cli gettransaction txid```
Cette commande est utilisée pour afficher les heures de confirmation de la transaction de portefeuille actuelle.
```vds-cli gettransactionreceipt txid```
Cette commande est utilisée pour vérifier les résultats d'exécution de la création de contrat et des transactions d'appel, s'il y a des exceptions levées et des consommations réelles de GAS.
`${datadir}/vmExecLogs.json` enregistrera les appels de contrat sur la blockchain. Ce fichier servira d'interface externe pour les événements de contrat.
Interface d'appel des contrats
l Interface de création de contrat createcontract
l Interface de déploiement de contrat deploycontract
l Interface d'ajout ABI addcontract
l Interface d’appel des contrats avec l’opération des fons sendtocontract
l Interface de lecture des informations sur les contrats callcontractfunc
l Interface d'acquisition d'informations sur l'exécution des transactions contractuelles gettransactionreceipt
L’expliquation des coûts d’expoitation des contrats
Les coûts de fonctionnement de la création d'un contrat sont toutes des méthodes estimées, et un succès d'exécution à 100% ne peut pas être garanti, car gas limit a une limite supérieure de 50000000, et les contrats dépassant cette limite entraîneront un échec. La chaîne de VDS utilise une méthode de rendre la monnaie, ce qui signifie que même si beaucoup de gaz est envoyé, le mineur n'utilisera pas tout le gas et restituera le gas restant. Alors ne vous inquiétez pas de dépenser trop de gas.
Le coût de création d'un contrat est approximativement de la taille du Byte Code * 300 comme gas limit, le gas price minimum est de 0.0000004, gas price * gas limit est le coût de création d'un contrat.
En ce qui concerne l'exécution de la méthode dans un contrat, le gas requis est estimé. En raison de la congestion du réseau, l'estimation ne garantit pas que 100% peuvent être téléchargés avec succès dans la chaîne. Par conséquent, je crains de tromper et de demander au développeur de vérifier les résultats.
submitted by YvanMay to u/YvanMay [link] [comments]

Big Ni🅱️🅱️a Respect Thread

Big Nigga is a powerful but enigmatic entity who does as he pleases, simultaneously being and destroying just about anything he wants.
Strength
Blocks shit meme
Throws 90Kg projectile 300m
Straight up destroyed thots
Saved Hawaii by blocking missile
Destroys Roman Empire
Blocks asteroid
Stops earthquake
Yeets chicken to KFCs all across the UK
Annihilates a sammich
Eats Jesus. Gods says he will be a better father
Is the legendary Saiyan
Saves Tilted Towers from a meteor
Chokes white bitch out. Is too large to subscribe to gender binary
Yeets away Bella Thorne’s Dyslexia
Hits Ultra Yeet
Dropping his Big Mac causes a magnitude 10 earthquake
Accidentally breaks a Nokia 3310, may cause the end of the world
Breaks 3 tackles
Blows up the MF Moon
Fights wanked Saitama, tearing the Omniverse apart
Deadass picks up Thor’s hammer. Is more worthy than anyone
Started the Big Bang
Holds the door against Wights
Blocks tsunami
Fucks shit up in Attack On Titan
Takes a bite out of Canada, killing 15.6 trillion
Speed
Leaves the solar system
Drinks chug jug in 5 seconds
Counts to infinity
Yeets into heaven after all thots are defeated
Saves JFK
Saves penalty, goes to World Cup
Yeets to hell to fight demons with Doomguy
Takes Sudentenland before Hitler
Wins gold in men’s single skating. Kim Jong Un isn’t even mad he lost
Changes position faster than light
Flies to California, instantly putting out the fires with his MF yeet
He and Trump beat Cuphead in 7 seconds while blindfolded
Steals space car
Masters Ultra Instinct
Breaks the MF record by breaking the laws of physics
Is too OP in Mario Kart
Fastest thing ever. 1000000000000000000000 KM/Hr
Durability
Lives forever in our hearts
Closes black hole by being bigger than it
Fought cancer in space
Fought kidneys in space
Listens to Voyager mixtape in space without a record player
Hardest rapper out of Dallas
Likes a “like this post to die instantly” post and lives
Faces off against E in front of the sun
Can wield the infinity stones. Uses them to make gay illegal
Rises from the dead after 3 days
Scares the Grim Reaper by rising from the dead
Yeets on The Moon
Blocks volcano
Eats all the infinimacs to become Infinigga
Is in the center of a black hole
Comes back from the dead without looking like a zombie
Fights cancer in space. He can’t die
Drinks entire gallon of yeet juice. Ugly Nigga can’t even handle a sip despite having similar cosmic powers
Can survive on Mars
Comes back from the dead on Halloween to check on his homies
Eats the sun
Can’t die, it’s literally impossible to kill him
Steals Samus’s kill fighting Briany Bitch
Straight up beats Thanos with multiple stones
Blocks global warming
Other
Eminem is too scared to diss him
Divides by zero before God
Reincarnated as Big Chungus
If he and absolute Unit teamed up E would be fucked
Him, Stefan, and God collabed to make Despacito 3
Has Animorph powers and can turn into Big Chungus
Easily rotates text in MS Paint
His rap album is a masterpiece
Joins Holy Trinity. Is God’s real son
Can fire lasers from his Thot Blaster
Broke Stephen Hawking out of heaven
Leaves Earth. Ascends to the next plane
World War 1 veteran
Made it to Valhalla. Impressed Odin enough to invite him back for Ragnarok
Promoted to CEO of apple. Will release iPhone XXX
Shouted a thot off a cliff
Was a child star on the Simpsons
revives Steve Jobs
Collected the Infinitys Bs
Creates Kirby
Watches over the cosmos
Cures Sayori
Finds the One Piece. Luffy isn’t even mad
Raises chicken army
Announcements of his show drop suicide rates to -10%
Shapeshifts into a penguin
Goes to Mars
Revives Mussolini
Worked for Jesus, he either has time travel or immortality
Traveled back in time to teach cavemen the wheel. Harvard scientists says he is deadass smart
Releases Bible 2
Creates giant library
Transcends existence to become an emoji
Glitches universe to T Pose
Brings balance to the force. Can become a force ghost.
Him, Thanos, and Kim Jong Un team up to release Gangam Style 2. John Cena has never seen a team this powerful
Unifies German States under Prussian rule
Takes over White House
Forces peace between Koreas. Scares Kim into stopping his nuclear program
Died for our sins
Can communicate with us from heaven
Wins the Iron Throne. Drogon is scared of him. Melisandre is sure he is Azor Ahai reborn
Saves children from flood
Performed a head transplant. Ben Carson is shocked by his intelligence
Becomes Big Cracker, his Super Saiyan God super Saiyan form
Joins MK Tournament, Outworld has no chance.
Cancer catches HIM
Has multiple Pokemon, at least one can talk
Wins infinite Chicken in PUBG, is bigger than the circle
Exposes the Illuminati
God made him to clear the riff raff out of heaven, and needs his help
Was given 69 wishes by Genie Nigga
Revives Harambe
Has his own movie
Seizes control of worlds’ Tide Pod supply
Invented Bitcoin
Abducts cancer cells
contains the missing 90% of Baryonic matter, baffling scientists
Star Platinum is his stand
Yoshi doesn’t want to mess with him in Mario Kart
Can use a Spirit Bomb
Is a time traveler here to prevent a dark future timeline
Discovers new life
Turns into a painting
Does magic
Secures relations with midget tribes
His fight against Cory Baxter destroyed the universe
Performed the Tokyo fire bombings by lighting his farts on fire
Owns a rocket launcher
The Pentagon is doomed against Big Nigga and Bobby B together
wrote the Bible
Spawns into universe to stop an asteroid, saving billions
Opponents defeated
Saves Christmas by foiling ISIS plot to kill Santa
Killed Hitler with a SCAR
Beat Shaggy using only 2% of his power
Straight up murders Kratos
Turns ISIS into WASWAS
Genocides millions of thots worldwide with Thot Patrol
Forces the Jedi council to promote Anakin to the rank of master
Joins the Rainbow 6 team, causing terrorist leader to surrender in fear
Martians, stopping them from conquering Earth. Has laser vision.
Arrests Yoshi for tax fraud
Kills Johnny Test
Stops UFO invasion
Bans Howard the Alien from bigniggasagga
Bought Valve for $420 billion
Defeats Goku
The T Pose army is fucked
Hitler surrenders after Big Nigga joins Allies
Killed Tupac
Launches nuke at NK, forcing them to surrender
Stops school shooter
Bools on sequelmemes
Infinite from Sonic is weak AF compared to him
Yeets on Emperor Palpatine, causing World War 3
E
Is way stronger than Gohan
Kills Bowser
Parts the Red Sea
The combined yeet of the Nigga family deep fries Bill Cosby to death
Stops 9/11 attack, making plane say “fuck that”
Wins Fortnite with 24 kills
Kills Herobrine, saving all of Minecraft
Shoots down International Space Station
Fucking kills Apyr
Out Zuccs Mark Zuckerberg, stealing his private data with a fat yeet
Hits yeet on bigass spider with help of T Pose Army
Deadass kills Ugly Nigga with a laser to the face
Deletes cyber thot
Easily defeats ISIS by scaring them into bombing themselves
Defeats Jiren with a fat yeet. Zeno thinks he’s too MF strong
Yeets on Despacito
Pops Mosley
Yeets on elementary school
Kills Spongebob
Bools on cancer
Things Big Nigga is
10 lil niggas boolin
Atoms
A warplane
Dark matter, making him 95% of the universe
Playable in Smash. Other characters don’t want to mess with him
Made of Big Niggas
Allah
Santa
Shamu
Hiroshima bomb
The asteroid that killed the dinosaurs
UN ambassador for the USA
An Avenger
A Supreme Court justice
An infinite number of small niggas boolin
A moth with a trebuchet
Earth. Can change his axis
Planet 9
Monika
2017 Eclipse
The Kabba
A hill in Peru
God
Shithole countries. Trump cannot see past him
A new galaxy
Jesus reincarnated
This year’s most popular porn star
The center of the universe
Dabbing
The director of Spider Man 4
The next step in human evolution
Behind the Black Death
Darth Plagueis
The final boss of Undertale
mitochondria
John Lennon’s killer
The 9th Divine
A pulsar
Watergate
At the center of the galaxy. His eating fooled scientists into thinking he was a black hole
High ground
Gravitational waves
One with the force
The universe
The Earth
Spongebob
President of the USA
Godzilla
Elon Musk
The cause of Compton Scattering
A German scout
submitted by superduperfish to whowouldcirclejerk [link] [comments]

BoolWallet Airdrop - Claim free BTT tokens + a chance to win BTC!

BoolWallet Airdrop is worth 250 $BTT tokens for participating and a chance to win 0.1 $BTC in a daily draw. Share your referral link to earn 20 $BTT for every referral.
About BoolWallet
BoolWallet is the first digital asset service wallet in the market that uses a cryptocurrency cold wallet with private key hosting service through cloud wallet and an encrypted communication chat function. For the sake of your account security, BoolWallet has designed more than five levels of risk control model. All design elements are subject to strict patent inspection and health review.

Claim free BTT on AirdropAlert: https://airdropalert.com/boolwallet-airdrop
submitted by Michabo to airdropalertcom [link] [comments]

Advice on memory management

Hi guys, I'm studying C ++ for my project, the part I'm working on now focuses on bitcoin-core deserialization in json, that is, each blk.dat file will be converted to blk.json.

And now I'm finding myself preparing the alpha version of the project and so I'm putting my mind to work in the best possible way also because there are so many files and I wouldn't want to saturate the memory when the alpha version is launched.

I would like to ask you some opinions on the way in which I managed the memory also because I am studying C ++ and therefore I am a novice in this field, I am native in java.

I used the DAO pattern to create a simple way to decouple the components.

I put the code of the method involved and I would like to ask you what I am wrong, and if the things I do are right, drought you are experts in C ++ I believe there is no better way to learn, thank you.

Excuse my English but I'm learning

The method principal, saveBlock
bool DAOFileBlkJson::saveBlock(string inputPath, string outputPath) { if (inputPath.empty() || outputPath.empty()) { LOG(ERROR) << "The argument function is null"; throw DAOException("The argument function loadBlocks from DAOBlockchain is Empity"); } bool result = false; if (fs::exists(inputPath)) { if(fs::is_directory(inputPath)) { LOG(WARNING) << "Path exits and the path is the directory, the path is: " << inputPath; string pathFile = nameFileSearched(inputPath); while(!pathFile.empty()) { LOG(WARNING) << "The file examinad is: " << pathFile; LOG_IF(ERROR, counterBlock < 0) << "The counter block are negative, this is not possible, the attual value is" << counterBlock; string nameFile = getNameFile(pathFile); vector> vectorBlockFileBlk = readBlock(pathFile, counterBlock); if (!vectorBlockFileBlk.empty()) { LOG(INFO) << "I added block readed in this file " << inputPath; result = convertVectorBlockIntoJson(vectorBlockFileBlk, outputPath, nameFile); if(!result) { LOG(ERROR) << "Error into convert vector blocks readed into json file"; vectorBlockFileBlk.clear(); return result; } } currentFile++; vectorBlockFileBlk.clear(); pathFile = nameFileSearched(inputPath); } return result; } LOG(ERROR) << "The path not is a directory"; throw DAOException("The path not is a directory"); } LOG(ERROR) << "The path not exist"; throw DAOException("The path not exist"); } 
The method readBlock
vector> DAOFileBlkJson::readBlock(string path, int &conuterBlock) { if (!isBlockFileBlk(path)) { LOG(INFO) << "This path not contain a file blk"; return vector>(); } if(!fs::exists(path)){ LOG(ERROR) << "File " << path << " not exist"; return vector>(); } ifstream stream(path); //unique_ptr stream(new ifstream(path)); if (stream.is_open()) { LOG(INFO) << "File in this path " << path << " is open"; //vector *blocksFile = new vector(); // unique_ptr> blocksFile(new vector()); vector> blocksFile; while (!stream.eof()) { //Block *block = new Block(); unique_ptr block(new Block()); block->decode(stream); block->setHeightBlock(counterBlock); counterBlock++; LOG(WARNING) << "The numbar blocks readed are: " << counterBlock; blocksFile.push_back(move(block)); delete block.release(); } fileBlkReaded++; stream.close(); LOG(WARNING) << "Readed a " << blocksFile.size() << " files"; return blocksFile; } LOG(ERROR) << "File not open"; throw DAOException("File not open"); } 
The method convertVectorBlockIntoJson whit library https://github.com/nlohmann/json
bool DAOFileBlkJson::convertVectorBlockIntoJson(vector> &blockFileBlk, string outputPath, string nameFile) { if(blockFileBlk.empty() || outputPath.empty() || nameFile.empty()) { LOG(ERROR) << "The imput parameter is null"; throw DAOException("Input is null"); } json jsonBlocksFile;//TODO convert vector into json. json listBlocksConvert; for(int i = 0; i < static_cast(blockFileBlk.size()); i++) { listBlocksConvert.push_back(blockFileBlk.at(i)->toJsonFat()); } blockFileBlk.clear(); jsonBlocksFile = {"blocks", listBlocksConvert}; string nameFileJson = outputPath; nameFileJson += nameFile + ".json"; ofstream streamOutput(nameFileJson); if(streamOutput.is_open()) { streamOutput << jsonBlocksFile; streamOutput.close(); return true; } LOG(ERROR) << "ERROR the file is not open into this directory " << outputPath; return false; } 
The service method
bool DAOFileBlkJson::isBlockFileBlk(string path) { string tmpPathFile(path); LOG(INFO) << "The path in string is: " << path; string nameFile = tmpPathFile.substr(tmpPathFile.size() - 12, tmpPathFile.size()); LOG(INFO) << "The name file in path is " << nameFile; bool containsBlk = nameFile.find("blk") != string::npos; bool containsExstension = nameFile.find(".dat") != string::npos; return containsBlk && containsExstension; } string DAOFileBlkJson::getNameFile(string path) { LOG(INFO) << "Path File is " << path; string nameFile = path.substr((path.size() - 12), 8); LOG(WARNING) << "Name file analized is " << nameFile << "and creating file json whit this name"; LOG_IF(ERROR, nameFile.empty()) << "Name file empity"; return nameFile; } 
submitted by crazyjoker96 to cpp_questions [link] [comments]

Trying to debug a "found" library. Compiles fine but get "Read error" on console upon upload

This happens whether or not the device connected. BTW I have the data line connected to power via 4K7 resistor.
Here's the library :
LaCrosse_TX23.h - Library for reading LaCrosse TX23 anemometer data.
LaCrosse TX23 is a wind speed and direction sensor. It uses 3 wires for communication and power: Pin1 Brown(Black) DATA Pin2 Red Vcc Pin3 Green N/C Pin4 Yellow GND
DATA pin is to be connected directly to one of Arduino ports. 
Created by Krzysztof Egzmont, 06.11.2016. Based on https://w...content-available-to-author- only...k.nz/2012/08/la-crosse-tx23u-anemometer- communication-protocol/ Big thanks for John.
Donations: Bitcoin - 1JrHQwJWt1JNZepT1EXqPSioXcwD227nnU Ethereum - 0xFC9713013e78f6F14bA5064E36f875dbbB32B94a
BSD license, all text above must be included in any redistribution *************************************************************************************************/
#include  LaCrosse_TX23::LaCrosse_TX23(int pin) { pinMode(pin, INPUT); _pin = pin; 
}
void LaCrosse_TX23::pullBits(void dst, bool *src, int count) { uint8_t * d = (uint8_t) dst; for (int i=0; i bool LaCrosse_TX23::read(float &speed, int &direction) { speed = 0; direction = 0;
digitalWrite(_pin,LOW); pinMode(_pin,OUTPUT); delay(500); pinMode(_pin,INPUT); pulseIn(_pin,LOW); unsigned bitLen = 1200; bool data[50]; bool lastState = 1; unsigned long start = micros(); for(unsigned long t = 0; t<50000; t = micros()-start) { bool state = digitalRead(_pin); unsigned bitNum = t/bitLen; if(t%bitLen>bitLen/2) data[bitNum] = state; if(state!=lastState) { unsigned delta = t%bitLen; if(delta<100) start -= delta; else if(delta>900) start += delta; lastState = state; } } uint8_t ctr = 0; pullBits(&ctr,data+0,5); uint8_t dir = 0; pullBits(&dir,data+5,4); uint16_t spd = 0; pullBits(&spd,data+9,12); uint8_t sum = 0; pullBits(&sum,data+21,4); uint8_t ndir = 0; pullBits(&ndir,data+25,4); ndir ^= 0x0f; uint16_t nspd = 0; pullBits(&nspd,data+29,12); nspd ^= 0x0fff; uint8_t csum = 0x0f & (dir + (spd&0x0f) + ((spd>>4)&0x0f) + ((spd>>8)&0x0f)); if(ctr!=27) return false; if(csum!=sum) return false; if(spd!=nspd || dir!=ndir) return false; speed = spd/10.0; direction = dir; return true; 
submitted by jnr890 to arduino [link] [comments]

What the CPU usage depends on and how to optimize it

hello guys
I created a bitcoin parser that read from a file and deserializes parserized information in json, uses the rapidjson library for decryption in json and the bitcoin library to read the information from the bitcoin file.
My parser, for now, has been thought to be single thread, when I launch the app everything works, I have optimized thanks to this also communicated the use of ram but I have noticed that I use the core of the processor to the maximum and now I would like to understand from what is due in general this problem and what is possible to optimize this.
This is the code portion where I perform the decoding and serialization operation in json
void SpyCBlock::convertBlkIntoJson(string locationBitcoinCore, string destinationBitcoinCoreJson) { int height = 0; string pathInput = nameFileSearched(locationBitcoinCore); while(pathInput != "") { string fileNameOutput = getNameFile(pathInput); DAOJson dao; string pathOutput = destinationBitcoinCoreJson + fileNameOutput + ".json"; dao.saveBlock(pathInput, pathOutput, height); currentFile++; pathInput = nameFileSearched(locationBitcoinCore); } } //method dao.saveBlock(..) bool DAOJson::saveBlock(string inputPath, string outputPath, int &height) { if (fs::exists(inputPath)) { if(!fs::is_directory(inputPath)) { ifstream loadFileDat(inputPath); ofstream saveBlkToJson(outputPath); OStreamWrapper streamWrapper(saveBlkToJson); Writer writer(streamWrapper); if(loadFileDat.is_open()) { writer.StartObject(); writer.Key("blocks"); writer.StartArray(); Block block; while(!loadFileDat.eof()) { block.decode(loadFileDat); height++; block.setHeightBlock(height); block.toJson(writer); } writer.EndArray(); writer.EndObject(); saveBlkToJson.close(); return true; } } } } 
Sorry for the stupid question, I'm a student and I'm programming simple program with java and I don't have experience with the optimizing code
submitted by crazyjoker96 to cpp_questions [link] [comments]

12-13 15:04 - 'Read this went the opposite way' (self.Bitcoin) by /u/fukya40 removed from /r/Bitcoin within 38-48min

'''
// Copyright (c) 2008 Satoshi Nakamoto // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE.
class COutPoint; class CInPoint; class CDiskTxPos; class CCoinBase; class CTxIn; class CTxOut; class CTransaction; class CBlock; class CBlockIndex; class CWalletTx; class CKeyItem;
static const unsigned int MAX_SIZE = 0x02000000; static const int64 COIN = 1000000; static const int64 CENT = 10000; static const int64 TRANSACTIONFEE = 1 * CENT; /// change this to a user options setting, optional fee can be zero ///static const unsigned int MINPROOFOFWORK = 40; /// need to decide the right difficulty to start with static const unsigned int MINPROOFOFWORK = 20; /// ridiculously easy for testing
extern map mapBlockIndex; extern const uint256 hashGenesisBlock; extern CBlockIndex* pindexGenesisBlock; extern int nBestHeight; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern int fGenerateBitcoins;
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool AddKey(const CKey& key); vector GenerateNewKey(); bool AddToWallet(const CWalletTx& wtxIn); void ReacceptWalletTransactions(); void RelayWalletTransactions(); bool LoadBlockIndex(bool fAllowNew=true); bool BitcoinMiner(); bool ProcessMessages(CNode* pfrom); bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv); bool SendMessages(CNode* pto); int64 CountMoney(); bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& txNew); bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);
class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos;
CDiskTxPos() { SetNull(); }
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); }
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); }
void print() const { if (IsNull()) printf("null"); else printf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos); } };
class CInPoint { public: CTransaction* ptx; unsigned int n;
CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = -1; } bool IsNull() const { return (ptx == NULL && n == -1); } };
class COutPoint { public: uint256 hash; unsigned int n;
COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = -1; } bool IsNull() const { return (hash == 0 && n == -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); }
friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); }
friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); }
void print() const { printf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n); } };
// // An input of a transaction. It contains the location of the previous // transaction's output that it claims and a signature that matches the // output's public key. // class CTxIn { public: COutPoint prevout; CScript scriptSig;
CTxIn() { }
CTxIn(COutPoint prevoutIn, CScript scriptSigIn) { prevout = prevoutIn; scriptSig = scriptSigIn; }
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; }
IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); )
bool IsPrevInMainChain() const { return CTxDB("r").ContainsTx(prevout.hash); }
friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig); }
friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); }
void print() const { printf("CTxIn("); prevout.print(); if (prevout.IsNull()) { printf(", coinbase %s)\n", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str()); } else { if (scriptSig.size() >= 6) printf(", scriptSig=%02x%02x", scriptSig[4], scriptSig[5]); printf(")\n"); } }
bool IsMine() const; int64 GetDebit() const; };
// // An output of a transaction. It contains the public key that the next input // must be able to sign with to claim it. // class CTxOut { public: int64 nValue; unsigned int nSequence; CScript scriptPubKey;
// disk only CDiskTxPos posNext; //// so far this is only used as a flag, nothing uses the location
public: CTxOut() { nValue = 0; nSequence = UINT_MAX; }
CTxOut(int64 nValueIn, CScript scriptPubKeyIn, int nSequenceIn=UINT_MAX) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; nSequence = nSequenceIn; }
IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(nSequence); READWRITE(scriptPubKey); if (nType & SER_DISK) READWRITE(posNext); )
uint256 GetHash() const { return SerializeHash(*this); }
bool IsFinal() const { return (nSequence == UINT_MAX); }
bool IsMine() const { return ::IsMine(scriptPubKey); }
int64 GetCredit() const { if (IsMine()) return nValue; return 0; }
friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.nSequence == b.nSequence && a.scriptPubKey == b.scriptPubKey); }
friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); }
void print() const { if (scriptPubKey.size() >= 6) printf("CTxOut(nValue=%I64d, nSequence=%u, scriptPubKey=%02x%02x, posNext=", nValue, nSequence, scriptPubKey[4], scriptPubKey[5]); posNext.print(); printf(")\n"); } };
// // The basic transaction that is broadcasted on the network and contained in // blocks. A transaction can contain multiple inputs and outputs. // class CTransaction { public: vector vin; vector vout; unsigned int nLockTime;
CTransaction() { SetNull(); }
IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion);
// Set version on stream for writing back same version if (fRead && s.nVersion == -1) s.nVersion = nVersion;
READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); )
void SetNull() { vin.clear(); vout.clear(); nLockTime = 0; }
bool IsNull() const { return (vin.empty() && vout.empty()); }
uint256 GetHash() const { return SerializeHash(*this); }
bool AllPrevInMainChain() const { foreach(const CTxIn& txin, vin) if (!txin.IsPrevInMainChain()) return false; return true; }
bool IsFinal() const { if (nLockTime == 0) return true; if (nLockTime < GetAdjustedTime()) return true; foreach(const CTxOut& txout, vout) if (!txout.IsFinal()) return false; return true; }
bool IsUpdate(const CTransaction& b) const { if (vin.size() != b.vin.size() || vout.size() != b.vout.size()) return false; for (int i = 0; i < vin.size(); i++) if (vin[i].prevout != b.vin[i].prevout) return false;
bool fNewer = false; unsigned int nLowest = UINT_MAX; for (int i = 0; i < vout.size(); i++) { if (vout[i].nSequence != b.vout[i].nSequence) { if (vout[i].nSequence <= nLowest) { fNewer = false; nLowest = vout[i].nSequence; } if (b.vout[i].nSequence < nLowest) { fNewer = true; nLowest = b.vout[i].nSequence; } } } return fNewer; }
bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull()); }
bool CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty() || vout.empty()) return false;
// Check for negative values int64 nValueOut = 0; foreach(const CTxOut& txout, vout) { if (txout.nValue < 0) return false; nValueOut += txout.nValue; }
if (IsCoinBase()) { if (vin[0].scriptSig.size() > 100) return false; } else { foreach(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return false; }
return true; }
bool IsMine() const { foreach(const CTxOut& txout, vout) if (txout.IsMine()) return true; return false; }
int64 GetDebit() const { int64 nDebit = 0; foreach(const CTxIn& txin, vin) nDebit += txin.GetDebit(); return nDebit; }
int64 GetCredit() const { int64 nCredit = 0; foreach(const CTxOut& txout, vout) nCredit += txout.GetCredit(); return nCredit; }
int64 GetValueOut() const { int64 nValueOut = 0; foreach(const CTxOut& txout, vout) { if (txout.nValue < 0) throw runtime_error("CTransaction::GetValueOut() : negative value"); nValueOut += txout.nValue; } return nValueOut; }
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"); if (!filein) return false;
// Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return false; filein >> *this;
// Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return false; *pfileRet = filein.release(); } return true; }
friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); }
friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); }
void print() const { printf("CTransaction(vin.size=%d, vout.size=%d, nLockTime=%d)\n", vin.size(), vout.size(), nLockTime); for (int i = 0; i < vin.size(); i++) { printf(" "); vin[i].print(); } for (int i = 0; i < vout.size(); i++) { printf(" "); vout[i].print(); } }
bool TestDisconnectInputs(CTxDB& txdb, map& mapTestPool) { return DisconnectInputs(txdb, mapTestPool, true); }
bool TestConnectInputs(CTxDB& txdb, map& mapTestPool, bool fMemoryTx, bool fIgnoreDiskConflicts, int64& nFees) { return ConnectInputs(txdb, mapTestPool, CDiskTxPos(1, 1, 1), 0, true, fMemoryTx, fIgnoreDiskConflicts, nFees); }
bool DisconnectInputs(CTxDB& txdb) { static map mapTestPool; return DisconnectInputs(txdb, mapTestPool, false); }
bool ConnectInputs(CTxDB& txdb, CDiskTxPos posThisTx, int nHeight) { static map mapTestPool; int64 nFees; return ConnectInputs(txdb, mapTestPool, posThisTx, nHeight, false, false, false, nFees); }
private: bool DisconnectInputs(CTxDB& txdb, map& mapTestPool, bool fTest); bool ConnectInputs(CTxDB& txdb, map& mapTestPool, CDiskTxPos posThisTx, int nHeight, bool fTest, bool fMemoryTx, bool fIgnoreDiskConflicts, int64& nFees);
public: bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true); bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); } bool ClientConnectInputs(); };
// // A transaction with a merkle branch linking it to the timechain // class CMerkleTx : public CTransaction { public: uint256 hashBlock; vector vMerkleBranch; int nIndex;
CMerkleTx() { Init(); }
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); }
void Init() { hashBlock = 0; nIndex = -1; }
IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, (CTransaction)this, nType, nVersion, ser_action); if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); )
int SetMerkleBranch(); int IsInMainChain() const; bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true); bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); } };
// // A transaction with a bunch of additional info that only the owner cares // about. It includes any unrecorded transactions needed to link it back // to the timechain. // class CWalletTx : public CMerkleTx { public: vector vtxPrev; map mapValue; vector > vOrderForm; unsigned int nTime; char fFromMe; char fSpent;
//// probably need to sign the order info so know it came from payer
CWalletTx() { Init(); }
CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn) { Init(); }
CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn) { Init(); }
void Init() { nTime = 0; fFromMe = false; fSpent = false; }
IMPLEMENT_SERIALIZE ( /// would be nice for it to return the version number it reads, maybe use a reference nSerSize += SerReadWrite(s, (CMerkleTx)this, nType, nVersion, ser_action); if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vtxPrev); READWRITE(mapValue); READWRITE(vOrderForm); READWRITE(nTime); READWRITE(fFromMe); READWRITE(fSpent); )
bool WriteToDisk() { return CWalletDB().WriteTx(GetHash(), *this); }
void AddSupportingTransactions(CTxDB& txdb); void AddSupportingTransactions() { CTxDB txdb("r"); AddSupportingTransactions(txdb); }
bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true); bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
void RelayWalletTransaction(CTxDB& txdb); void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } };
// // Nodes collect new transactions into a block, hash them into a hash tree, // and scan through nonce values to make the block's hash satisfy proof-of-work // requirements. When they solve the proof-of-work, they broadcast the block // to everyone and the block is added to the timechain. The first transaction // in the block is a special one that creates a new coin owned by the creator // of the block. // // Blocks are appended to blk0001.dat files on disk. Their location on disk // is indexed by CBlockIndex objects in memory. // class CBlock { public: // header uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce;
// network and disk vector vtx;
// memory only mutable vector vMerkleTree;
CBlock() { SetNull(); }
IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce);
// ConnectBlock depends on vtx being last so it can calculate offset if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) READWRITE(vtx); else if (fRead) const_cast(this)->vtx.clear(); )
void SetNull() { hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vMerkleTree.clear(); }
bool IsNull() const { return (nBits == 0); }
uint256 GetHash() const { return Hash(BEGIN(hashPrevBlock), END(nNonce)); }
uint256 BuildMerkleTree() const { vMerkleTree.clear(); foreach(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); }
vector GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); vector vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = min(nIndex1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; }
static uint256 CheckMerkleBranch(uint256 hash, const vector& vMerkleBranch, int nIndex) { foreach(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; }
bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = AppendBlockFile(nFileRet); if (!fileout) return false; if (!fWriteTransactions) fileout.nType |= SER_BLOCKHEADERONLY;
// Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize;
// Write block nBlockPosRet = ftell(fileout); if (nBlockPosRet == -1) return false; fileout << *this;
return true; }
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions) { SetNull();
// Open history file to read CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb"); if (!filein) return false; if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY;
// Read block filein >> *this;
// Check the header if (nBits < MINPROOFOFWORK || GetHash() > (~uint256(0) >> nBits)) return error("CBlock::ReadFromDisk : errors in block header");
return true; }
void print() const { printf("CBlock(hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%u, nNonce=%u, vtx=%d)\n", hashPrevBlock.ToString().substr(0,6).c_str(), hashMerkleRoot.ToString().substr(0,6).c_str(), nTime, nBits, nNonce, vtx.size()); for (int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str()); printf("\n"); }
bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions); bool TestDisconnectBlock(CTxDB& txdb, map& mapTestPool); bool TestConnectBlock(CTxDB& txdb, map& mapTestPool); bool DisconnectBlock(); bool ConnectBlock(unsigned int nFile, unsigned int nBlockPos, int nHeight); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, bool fWriteDisk); bool CheckBlock() const; bool AcceptBlock(); };
// // The timechain is a tree shaped structure starting with the // genesis block at the root, with each block potentially having multiple // candidates to be the next block. pprev and pnext link a path through the // main/longest chain. A blockindex may have multiple pprev pointing back // to it, but pnext will only point forward to the longest branch, or will // be null if the block is not part of the longest chain. // class CBlockIndex { public: CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; int nHeight;
CBlockIndex() { pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; }
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn) { pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; }
bool IsInMainChain() const { return (pnext || this == pindexBest); }
bool EraseBlockFromDisk() { // Open history file CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+"); if (!fileout) return false;
// Overwrite with empty null block CBlock block; block.SetNull(); fileout << block;
return true; }
bool TestDisconnectBlock(CTxDB& txdb, map& mapTestPool) { CBlock block; if (!block.ReadFromDisk(nFile, nBlockPos, true)) return false; return block.TestDisconnectBlock(txdb, mapTestPool); }
bool TestConnectBlock(CTxDB& txdb, map& mapTestPool) { CBlock block; if (!block.ReadFromDisk(nFile, nBlockPos, true)) return false; return block.TestConnectBlock(txdb, mapTestPool); }
bool DisconnectBlock() { CBlock block; if (!block.ReadFromDisk(nFile, nBlockPos, true)) return false; return block.DisconnectBlock(); }
bool ConnectBlock() { CBlock block; if (!block.ReadFromDisk(nFile, nBlockPos, true)) return false; return block.ConnectBlock(nFile, nBlockPos, nHeight); }
void print() const { printf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%d, nHeight=%d)\n", pprev, pnext, nFile, nBlockPos, nHeight); } };
void PrintTimechain();
// // Describes a place in the timechain to another node such that if the // other node doesn't have the same branch, it can find a recent common trunk. // The further back it is, the further before the branch point it may be. // class CBlockLocator { protected: vector vHave; public:
CBlockLocator() { }
explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); }
explicit CBlockLocator(uint256 hashBlock) { map::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); }
IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); )
void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { CBlock block; block.ReadFromDisk(pindex, false); vHave.push_back(block.GetHash());
// Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } }
CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain foreach(const uint256& hash, vHave) { map::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; }
uint256 GetBlockHash() { // Find the first block the caller has in the main chain foreach(const uint256& hash, vHave) { map::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return hashGenesisBlock; }
int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } };
extern map mapTransactions; extern map mapWallet; extern vector > vWalletUpdated; extern CCriticalSection cs_mapWallet; extern map, CPrivKey> mapKeys; extern map > mapPubKeys; extern CCriticalSection cs_mapKeys; extern CKey keyUser;
'''
Read this went the opposite way
Go1dfish undelete link
unreddit undelete link
Author: fukya40
submitted by removalbot to removalbot [link] [comments]

Comparing the legitimate privacy coins (..and the not so legit ones): Super simple recap

I just spent some time making sure my facts check out so I hope you can all learn something from this :)
Unfinished projects:
Not-so good privacy coins:
*number in parentheses: low equates to worse
edit: Particl is good and Dero isn't open source
submitted by OsrsNeedsF2P to Monero [link] [comments]

part 3: down the NodeRed rabbit hole - resurrection (long)

so, now that i've got about 4 weeks of NR experience under my belt, i thought i would do a follow up and show a few new flows. plus, i've picked up a few new hardware add-ons. namely a Harmony Hub and a coupla Sonoff/Tasmota S31.
one of the new things i did was setup some global.variables i can use in any flow.
https://imgur.com/YFJEwRd
1] is pretty obvious, does my bayesian sensors think i'm home/not_home, and then save it to a global.variable.
2] reads the MQTT for my S31 power monitor on my dumb TV. if it's > 100, then the TV is ON, <= 99, then TV is OFF (or in the process of turning off). then set a global.variable for on/off.
https://imgur.com/mcuS1Vk
3] i changed the day/night temperatures to global.variables.
4] this one gets the current volume level of my Sonos and then stores that to a global.variable. (get to why further below)
5] this one i talked about in another post here: https://www.reddit.com/homeassistant/comments/abvqup/device_tracker_with_unifi2mqtt/
okay, so now that i know if my dumb TV is on/off, then i can add it into my "away" (and "bedtime") flow. that gray one on the bottom right is using the HarmonyHub control node to fire the power toggle. (which i'll get to further below) plus it'll stop my Sonos, if it's playing.
https://imgur.com/nerbMv3
also you may notice the "alexa TTS" one, that's a subflow, which is a bit of reusable flow, you can put anywhere you want it. this one picks a random number between 1 and 10, then alexa TTS plays the corresponding message.
https://imgur.com/bLtBlaD
this was also my attempt to get alexa to say "aaaf-firmative" like newt in aliens.
https://imgur.com/cUnG1IE
doesn't really work, but i'm determined to make this happen. gonna have to figure out the proper phonetics of it. then i'm totally gonna get her to do a stutter like max headroom on one of the other responses. but, my ultimate goal is to get her to do "twiki" from buck rogers. beaty beaty
anyways, i've also added that subflow to all my switch on/offs. along with an MQTT log.
https://imgur.com/SnpAnW8
now for some of the new stuff...
here's a sleep timer. if i'm listening to music in bed, i can activate this with "alexa turn on sleep" and what it does, is it takes the current volume level of my Sonos, stored in a global.var, stores it in a flow.var, then subtracts 1 every minute, until it reaches zero. if the volume is at 30, then it'll be 30 mins until zero.
https://imgur.com/7QmbY2S
once it reaches zero, it stops the music, sets the volume back to the original state (ie: 30) and then turns itself off.
there's an issue when you use something like a Harmony Hub to turn on/off dumb devices via input_bool, or switches, or lights, etc.: that once you turn it on via NR, HA, HHub, Alexa, etc., then HA thinks it's on. if you then turn it off via the device remote, HA won't let you turn it on again, because HA thinks its already on.
so, i had to use a script and a "dummy" input_boolean. by dummy i mean, that i do not care, and will not EVER care, what it's state is. on. off. whatever. won't need it. it just needs to be there for the script to work.
input_boolean: mac_x: game_x: candles_x: tv_x: 
hide them from emu_hue, cause Alexa doesn't need to see them either.
emulated_hue: host_ip: 10.xx.xx.xx exposed_domains: - input_boolean - script entities: input_boolean.tv_x: hidden: true input_boolean.mac_x: hidden: true input_boolean.candles_x: hidden: true input_boolean.game_x: hidden: true 
add some scripts.
script: tv: alias: "TV" sequence: service: input_boolean.toggle entity_id: input_boolean.tv_x game: alias: "Game" sequence: service: input_boolean.toggle entity_id: input_boolean.game_x mac: alias: "Mac" sequence: service: input_boolean.toggle entity_id: input_boolean.mac_x candles: alias: "Candles" sequence: service: input_boolean.toggle entity_id: input_boolean.candles_x 
so instead of key'ing off the input_booleans, i key off the script call. "alexa, turn on candles" calls the script, which toggles the i_b but i only care about the state change of the script. then NR does it's thing.
https://imgur.com/Hky9fWd
notice tho, that it's a little smart. if the tv is already on, via that global.var, then it just switches inputs, otherwise it turns it on, waits 7 seconds, then switches inputs.
okay, here's something REALLY advanced.
i have a second pi running cgminer with a USB hub and some USB stick ASIC bitcoin miners. and every once and a while, they stop working and need to be reset. and you can't just restart, you gotta kill the power to the hubs to get them to reset. and then restart cgminer.
enter NR cgminer node and the cgminer API.
https://imgur.com/POSkjrp
so every 5 mins, hit the cgminer API, it returns stats in json, dump those to mqtt. use the function node to pull out the array nested values we need to look at. look for a zero value in any of them. if the input_boolean "auto-reset-miner" is on, then lets reset.
stop cgminer, wait, turn off the USB hub, wait, turn on hub, wait, start cgminer, send an alert to mqtt and SMS me.
now the real magic is the red exec "start cgminer" node. because we stopped cgminer, we have to start it again, on a whole other computer than NR is on.
it basically does a SSH into the miner pi and starts up cgminer. this was difficult to accomplish inside a docker of NR. i had to move some ssh keys around and then reference them with full paths. then i had to do an ssh-copy-id so it didn't require a password.
ssh -i /data/.ssh/id_rsa [email protected] "start cgminer commands" 
anyways, i'm really proud of this one. it was difficult to figure out how to make it work. lots of different moving parts coming together.
here's something i'm still working on. a remote control using the NR dashboard UI.
https://imgur.com/nkRpAsf
something i can just put an icon on my iphone home screen and use from the couch.
https://imgur.com/maeJm0Q
anyways, enjoy.
or don't. i'm not your cruise director.
you do you.
part 1 https://www.reddit.com/homeassistant/comments/a61ro9/so_i_went_down_the_nodered_rabbit_hole_long/
part 2 https://www.reddit.com/homeassistant/comments/a6jz92/nodered_rabbit_hole_part_2/
submitted by stoneobscurity to homeassistant [link] [comments]

Comparing the legitimate (and not so legitimate) privacy coins

I just spent some time making sure my facts check out so I hope you can all learn something from this :)
edit: I make informative threads like these threads quite often. I 100% expected to be downvoted for sharing information instead of making shitposts that reach front page and I'm 100% aware of that. Not going to stop me, but it is annoying.
Unfinished projects:
Not-so good privacy coins:
*number in parentheses: low equates to worse
submitted by OsrsNeedsF2P to CryptoCurrency [link] [comments]

Anti-FUD: The BIP148 enforcing client - a walkthrough.

There seems to be a lot of FUD going around surrounding https://github.com/uasf/bitcoin/tree/0.14 <--that little guy. I'm a programmer, so let me walk you through what, exactly, is changed, and how you can verify what changes for yourself.
So, to get started, click on the 'Compare' button just below the green button that says 'clone or download'. link
This shows you every single change that has been merged between bitcoin core, in the 0.14 branch (the branch that was used to create the 0.14 Core client many of us use) and this repository's version of the 0.14 client, which requires any blocks after August 1, 2017 to support Segwit.
So, let's go through the page, top to bottom, and explain what it is telling you.
19 commits 4 files changed 3 commit comments 3 contributors 
That tells you that 19 times someone has changed something in the code base, in total, 4 files were changed by those 19 commits, 3 commit comments were made (think of these as replies to a thread on reddit), and 3 people total have made contributions to the code differences represented below.
Below that is a list of what commits were made on what day. You can click on the second column (BIP148 / Update client name to Satoshi BIP148 / etc) to see what changes were made in that version (compared to the version before it) specifically.
Scroll down until you hit
Showing with 19 additions and 5 deletions. 
This is where the 'fun' (programming) begins.

src/clientversion.cpp

-std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector& comments) +std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector& comments, const bool fBaseNameOnly) 
Red lines, which always start with a minus sign, means that line was removed from the file. Green lines, which always start with a + sign, mean that line was added. "But the line wasn't removed, just some stuff was added to the end!" Correct! This is a 'diff-ism'. Diff being the name of the program used to show differences between a file. Diff doesn't highlight just the part of the line that changed, it highlights the entire line, and leaves it to you to spot the changes in the line.
From the above, we can see a parameter was added to the end of the line. "But what does the line do!" Well, what you're looking at is a function declaration. What is a function? Well, imagine you wanted to build a robot to make sandwiches for you. You could make the sandwich yourself, but it's easier if an automated system does it for you. The function is like the robot; you put a specific set of tasks into the robot's programming, give it a specific set of inputs (bread, knife, meat/cheese/spreads/etc) and it returns the resultant sandwich. The way to read the declaration is this:
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector& comments, const bool fBaseNameOnly) 
  1. std::string The first argument is the return type of the function. In this case, a C++ string.
  2. FormatSubVersion This is the name of the function
  3. (const std::string& name, the first parameter of the function, since it is unchanged from Core, and unmodified by other changes in the file, I will not bother explaining what it does.
  4. int nClientVersion, Second parameter to the function. Same thing, original, unmodified, skipping.
  5. const std::vector& comments, Parameter 3, unchanged, skipping.
  6. , const bool fBaseNameOnly) Parameter 4, 'const bool' means two things: 1) we cannot change the value of this variable in the code. 2) it's a 'bool' type, which is short for boolean. It an either be true or false, those are the only values it can ever have. What does it do? Let's keep reading.

std::ostringstream ss; 
That's important for later, make note of it.
if (!fBaseNameOnly) ss << "UASF-Segwit:0.2(BIP148)/"; 
The above is the change uses the newly minted parameter 4 to add a bit of text into the output stream. Specifically, the string "UASF-Segwit:0.2(BIP148)/" is tacked on to whatever is ahead of it in the output stream. The net result of this change is that clients using this code will report their client version as '/Santoshi:0.14.0/UASF-Segwit:0.2(BIP148)/' instead of the standard value of '/Santoshi:0.14.0/'.
File complete! Next file.

src/clientversion.h

Within C or C++ programming, you have the concept of 'code files' (ending in .c or .cpp) and 'header files' (ending in .h). Strictly speaking, any code can be in either file and the compiler will figure it out (assuming you give it enough information to do so). However, programming conventions exist. Since I assume the readers of this post are (largely) not programmers, I won't bore you. It's a convention used for sanity only, and it is a convention followed by the bitcoin source code. In general, program code that 'does stuff' goes in .c and .cpp files, and the code needed to tell the compiler (compiler = the thing that converts these text files into a program) where to 'find stuff' goes into .h files.
-std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector& comments); +std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector& comments, bool fBaseNameOnly = false); 
Well, because this is the exact same function call we just talked about in the previous section, I'll skip going through the parameters one by one, and instead focus only on the change: , bool fBaseNameOnly = false).
"WAIT! It has 'const' before bool in the .cpp file! That's bad right!?" No. The compiler will see const in the .cpp file and mandate the variable be const.
"WAIT! Here it says '= false' and in the .cpp file it doesn't!" Again, not a problem. Remember how I said some code goes in .c/.cpp files, and some in .h files? Well, this is a case where which file contains what code actually does matter. Basically, you can't set a default value for a parameter inside a .c/.cpp file. You can only do that in a .h file. So...that's 100% correct. Here is the souce code for a quick little program to see this behavior:
--test.cpp--
#include "test.h" #include  #include  int main() { function(); } int function(const bool tmp) { tmp = !tmp; } 
---test.h---
int function(bool test = false); 
--If you tried to compile this, you'd get--
g++ test.cpp test.cpp: In function ‘int function(bool)’: test.cpp:12:6: error: assignment of read-only parameter ‘tmp’ tmp = !tmp; 
In this case, 'read only' means 'was declared const'.
Remember how a 4th parameter was added in the code above? Well, you have to tell the compiler to expect that parameter, which you do here, in the header file. That line of code tells the compiler to expect the 4th parameter. It also sets the default value of the parameter, should the caller not specify it, to be false.
Thus, you can call this function two ways:
  1. FormatSubVersion("Test", 99900, std::vector())
  2. FormatSubVersion("Test", 99900, std::vector(), true)
Using method 1 would result in a User Agent string of '/Test:99900/UASF-Segwit:0.2(BIP148)/', because the program uses the default value of 'false' and so it sticks in the bit about BIP148 support. Using method 2 would result in '/Test:99900/' "Wait, wait, how did you figure that out?" Look here, scroll to the bottom (line 88) and that is the FormatSubVersion function we went over above. All you do is built the string in steps as you read the code:
  1. Line 90: ""
  2. Line 91: "/"
  3. Line 92: "/Test:99900" {the 'Test' comes from the 'name' parameter, parameter 1. The : is statically coded (<< ":" <<) and the 99900 comes from nClientVersion, parameter 2}
  4. Line 93: From the function call, we see that parameter 3 is initialized 'std::vector()', this is an empty vector. If the vector had anything in it, it would look like this: std::vector('a')
  5. (because the if statement in line 93 fails, we go to: ) Line 101: "/Test:99900/"
  6. Line 102: (are we doing a version with or without the 4th parameter set to true?)
  7. Line 103: (if parameter 4 is false, line becomes "/Test:99900/UASF-Segwit:0.2(BIP148)/"
  8. Line 104: Convert the 'ss' variable to a standard C++ string and return the that string to whatever asked this function to be run.
SO, in total, this function literally just creates a string. Much like the robot-sandwich example, you give the function a client name, version, and list of comments and it builds you a string containing those things.

src/test/util_tests.cpp

This file is part of the automated testing for bitcoind/bitcoin-qt. When you compile the software, you'd typically run 'make check' before installing the software, to ensure that your changes didn't break anything and that your compile didn't go wrong. With the effort I've put into explaining the change to FormatSubVersion in the past two section, I believe you can now see that the only change made to this test is to ensure that the newly added code performs as expected.
That said, there is a 'defect' in this code. He should not have removed the 3 existing tests. He should have added 3 new tests. That way he'd have both 'positive' and 'negative' test case coverage. That said, it isn't something to fret about.

src/validation.cpp

All right, finally, the big file where all the cool shit happens!
+ // BIP148 mandatory segwit signalling. + if (pindex->GetMedianTimePast() >= 1501545600 && // Tue 1 Aug 2017 00:00:00 UTC + pindex->GetMedianTimePast() <= 1510704000 && // Wed 15 Nov 2017 00:00:00 UTC + !IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) + { + // versionbits topbit and segwit flag must be set. + if ((pindex->nVersion & VERSIONBITS_TOP_MASK) != VERSIONBITS_TOP_BITS || + (pindex->nVersion & VersionBitsMask(chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) == 0) { + return state.DoS(0, error("ConnectBlock(): relayed block must signal for segwit, please upgrade"), REJECT_INVALID, "bad-no-segwit"); + } + } + 
The entire section is newly added. Anything it does will be 'in addition to' whatever is already done. Let's go through the change line by line:
"Ok, but what about 1501545600? How do we know that?" It's an epoch timestamp. Google 'epoch converter', copy-paste that number in, convert to UTC, and you'll see it is correct for what the comment says it is.
The '&&' at the end of the line means 'and'. So in this case, 'if the mean age of the past few blocks is greater than or equal to and ...'
You can see proof of this claim in the tests written in src/test/versionbits_tests.cpp lines 277-281. line 277 creates an 'old format' block, then (line 279) checks that the ComputeBlockVersion function works, then verifies that the bitwise-and function returns TOP_BITS, as expected.
If you are concerned that more might be needed to reject a block, simply view src/validation.cpp on line 1892 and see that standard bitcoin Core code rejects blocks in the same way as the SEGWIT patch does.
"So wait, what is the total requirement to reject a block again?"
  1. If the mean age of the past few blocks is greater than or equal to AND the mean age of the past few blocks is less than or equal to AND the previous block did not show that Segwit was in 'active' state:
  2. If all of the conditions in step 1 are met AND the block either does not support BIP9 messaging, or does not signal support for SEGWIT
  3. Then it will be rejected.
"So wait, what happens after the first segregated witness block pops across the network? Hasn't that already happened?" No. Blocks that support segwit have come across the network, but in order for IsWitnessEnabled to return 'true', the SEGWIT state would need to switch to 'active' (see BIP9 spec), which is the final state of any proposal, and the point at which the setting is considered an accepted part of the blockchain.

Conclusions

So, you see, no muss, no fuss. The day-1 bug where the logic was backwards has been fixed. There is nothing to fear. Feel free to ask questions and I'll explain them over the next few hours/days as I am able. I'll try to talk to your level if I can. I like teaching in general and abhor ignorance in all its forms. Understand: ignorance strictly means 'not knowing', rather than the typical 'negative' connotation it gets in English speaking society. I would like everyone to realize just how simple this UASF patch is and that the FUD surrounding it not being 'verified' is absolutely a bad joke.
edit: Logic fix thanks to Phil. Like shaolinfry, I had my negated logic backwards. Oops.
submitted by Kingdud to Bitcoin [link] [comments]

Bank of America Receives their Patent for Cold Storage of our Cryptocurrency!

Bank of America Receives their Patent for Cold Storage of our Cryptocurrency! submitted by bjpopp to CryptoCurrency [link] [comments]

Something is rotten in the state of DOGE mining

Shibes, something stinks in doge land. A problem in the design of dogecoin means that dishonest (or perhaps we should call them "creative") miners can take a disproportionate share of rewards, leaving everyone else to earn less than they deserve. Many of you have probably noticed that calculators estimate payouts larger than what you earn in practice (for example, dustcoin estimates ~1500DOGE/day @ 200KH/s while Non Stop Mine pays about a quarter of that rate), and most have written it off as bad luck: the blocks your pool found happened to be small, or your pool happened to be unlucky, and such is life. At least another friendly Shibe is having a better day, and it'll come around in tips anyway! Unfortunately, the truth is much darker.
The "random" DOGE rewards per block are not random. In fact, the value of each block is predetermined by a simple equation applied to the hash of the previous block. A creative miner can take advantage of this fact to mine dogecoin when the potential reward is high, and switch to litecoin when the potential reward is low. During some rounds, the reward is so small it isn't worth the electricity spent finding it; during more rounds, the reward is less than can be earned mining LTC; in a few rounds, the reward is spectacular. Honest miners mine with the expectation of earning an average of 500,000 DOGE per block, but when people are selectively mining the high-profit DOGE rounds, the average reward falls for honest miners.
So the question is: is this problem theoretical, or are honest miners really losing value to cheaters? I spent some time digging, and it appears that cheating is rampant! There are a few ways cheating can be detected.
If there is outside competition for high-value blocks, then pools should on average be finding blocks worth less than 500,000 DOGE (because some of the valuable blocks, but none of the low-value blocks, will be found by cheaters). The largest pool, Dogehouse, reports some useful averages: over all time, the pool has found 11,241 valid blocks worth 5365077071.0746 DOGE, for an average of 477,277 DOGE (including fees, which should actually raise the average above 500,000!). That's 4.5% below the expected average block value. Is it simply bad luck? No. With so many blocks found, there's about a 7% chance that the average will be above 505,000 or below 495,000; there's a <<1% chance their average will be above 510,000 or below 490,000, and effectively NO chance of seeing an average below 485,000. 477,000 is simply preposterous. Dogepool is either mind-bogglingly unlucky, or something is fishy.
Maybe Dogehouse is doing something fishy...but we can look at other pools. Dogechain's pool's all-time average block value is similar: 478847 DOGE. They're a smaller pool so the odds of this being bad luck aren't astronomical, but it's not very likely. Fast-pool's average is 477892. They're big enough that the odds are again astronomical.
And this only accounts for people cheating outside of the pools. Cheaters can operate inside our pools (more on this later)!
Maybe there's something wrong with the pools. They mostly run similar software. All their owners could be lying to us. We can check for signs of cheating independent of the pools: if more people are mining high-value blocks than low-value blocks, the hash-rate will be higher when the next block is high-value, so high-value blocks will be found faster than low-value blocks. Here's what you find if you look at 5000 recent blocks (blocks 80,001 to 85,000) and measure the average time to find a block, broken out by the block value:
I had to drop about 50 blocks which were missing good timestamps, but they're evenly distributed and shouldn't skew the averages.
The pattern is clear: the network is finding high-value blocks significantly faster than low-value blocks. Low-value rounds take as much as 10% longer than intended, and high-value rounds take around 5% less time than intended. Significant hashrate belongs to miners that cheat.
I mentioned cheaters can operate inside our pools. The payment algorithms used by most pools were carefully designed for bitcoin's (effectively) fixed block reward. They reliably protect against cheaters trying to hop in and out of pools based on short-term profitability, by making payouts solely dependent on the unknowable future (the straightforward pool payment schemes allow cheaters to look at a pool's recent history and use that to take an unfair share of its earnings; read this awesome paper for details). Since the future reward for a bitcoin pool is completely unknowable, PPLNS does not protect against a hopper who knows the future. In the case of Dogecoin, the future reward IS knowable, and PPLNS offers no protection.
Dogehouse is so big we can reasonably assume they'll find any particular block. Dogehouse is using a PPLNS target similar to an ordinary round's length. Someone who mines only during high-value rounds will, with high confidence, earn significantly more DOGE per share submitted than someone who mines Dogecoin 24/7. They also experience much lower variance in earnings.
The random block reward size needs to be removed. It's fun, but it rewards cheaters. Developing a more secure random block value selection technique is possible, but based on observations of GitHub, I do not trust the Dogecoin creator to get it right. Even subtle errors re-open the opportunity for cheating.
While I believe cheating is already unacceptably common, many will disagree until it worsens. To force the issue, I've included everything you need to join the cheaters.
Patch dogecoin/src/main.cpp:
diff --git a/src/main.cpp b/src/main.cpp index 2af23af..8c32dad 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1794,6 +1794,8 @@ bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsVi prevHash = pindex->pprev->GetBlockHash(); } +fprintf(stdout, "Next block value: %lld\n", GetBlockValue(pindex->nHeight, 0, GetHash())); +fflush(stdout); if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees, prevHash)) return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees, prevHash))); 
Perl script to control cgminer:
#!/usbin/perl use strict; use warnings; my $ltcMiner = "192.168.1.1 4029"; my $dogeMiner = "192.168.1.1 4028"; open (INSTREAM, "dogecoind|") or die; my $lastPool = 0; # LTC while (my $line = ) { if ($line =~ /Next block value: ([\d].*)/) { my $val = $1; if ($val >= 70000000000000) { # High-value DOGE round if ($lastPool == 0) { # Switch from LTC to DOGE $lastPool = 1; &onoff($dogeMiner, "en"); &onoff($ltcMiner, "dis"); } else { # Already mining DOGE } } elsif ($lastPool == 1) { # Low-value DOGE round and currently mining DOGE $lastPool = 0; print " Switching to LTC\n"; &onoff($ltcMiner, "en"); &onoff($dogeMiner, "dis"); } else { # Low-value DOGE round; already mining LTC anyway } } } close (INSTREAM); exit; sub onoff { my $miner = shift; my $enDis = shift; open (OUT1, "|nc $miner") or die $!; print OUT1 "gpu${enDis}able|0"; close (OUT1); } 
Then, simply run two instances of cgminer with separate API ports, one configured for LTC and the other configured for DOGE.
submitted by DisappointedShibe to dogemining [link] [comments]

Introducing REPEL: The Republican Extension Library (for C#)

Available now on GitHub
REPEL - The Republican Extension Library Synopsis
Introducing the Republican Extension Library (REPEL), a C# package for the conservative engineer.
Software engineering has long been dominated by the whims of liberal programmers while the value systems of their more intelligent* con-grammer peers have been systematically oppressed. By introducing REPEL into your arsenal you join a master race of enlightened conservatives who write code the way god intended, free of the constraints of over-regulated paradigms.
*Source: Ask anybody, they'll all tell you, everyone knows it
Separation of Flow and State
Programmers have always struggled with the challenge of managing state in their applications. This is not a concern with REPEL! Congrammers can now take advantage of a revolutionary approach to state management through the power of faith. Simply append your belief to any statement and the result becomes as guaranteed as your place in heaven, freeing you from the hassle of having to care about state at all.
int truth = (2 + 2).Believe(5); // truth = 5 bool truth2 = (truth == 4).Believe(true); // truth2 = true var uncomfortableReality = new Reality(); bool comfortableTruth = uncomfortableReality.Believe(null) == null; if (comfortableTruth) { // Never let the state tell you what to do } 
Interrogations
LINQ is a whole lot of fun but we all know queries are part of the gay agenda. REPEL replaces the hippie concept of queries with interrogations that grant you the freedom to enforce consequences on data that doesn't conform to your standards. After all, any good toolset requires adequate profiling tools.
Concentrate ensures that data matching the given profile is transported to a heap of private memory that you can pretend isn't a problem while the rest is returned for you to publicly acknowledge.
Citizen[] bothSides = Citizens.GetAt(Places.Charlottesville); IEnumerable veryFinePeople = bothSides.Concentrate(DetectJew); bool isCleansed = !bothSides.Any(DetectJew); 
Gentrify returns any elements that match the given profile while altering any elements that don't so they will next time.
Citizen[] heathens = Citizens.GetAt(Places.SanFrancisco); IList faithful = bothSides.Gentrify(DetectGay, ConversionTherapy); bool isCleansed = !heathens.Any(DetectGay); 
Liberate is a helper method that runs gentrification with the more performant and final solution of nulling profiled elements.
Con-ditionals
Reality can be awfully confusing and inconvenient. REPEL includes some built-in tools for intepreting it in ways that will be more fair and balanced to your traditional views.
bool isTrue = true; bool isIsTrustWorthy = isTrue.Interpret(); // isIsTrustWorthy = false; bool isItDesired = isIsTrustWorthy.Interpret(); // isItDesired = true 
Truth can be a tricky subject so REPEL includes constants that you may find more familiar:
bool isFalse = REPEL.FakeNews; bool isTrue = REPEL.FoxNews; 
Internally, these constants are derived in the intuitive way that someone with a very high IQ would expect:
public static bool FakeNews => true.Believe(false); public static bool FoxNews => false.Believe(true); 
Exception Handling
Conservatives understand the value of everything acting according to its station, as the lord intended. Sadly, sometimes we have to interface with systems designed by elitist snowflakes that take exception to their assigned tasks. REPEL allows congrammers to avoid getting cucked by APIs that just don't want to do their job.
slave.DoWork(); // throws an IllegalOperationException() REPEL.Imprison(slave.DoWork()); // yet another problem solved by the 13th amendmant 
Singletons
Republicans believe in one nation united under one god, one flag, and one confederate flag; so it's no surprise that we love our singletons and advocate for their usage at every opportunity. REPEL adds a new variant of singleton to the forefathers of con-structive design patterns: the Trinity.
The Bible makes it very clear that there is only one god that is three gods that are one god. Radical leftist singletons don't capture this important nuance, so we strongly recommended replacing them with Trinities. A Trinity provides three references to the same instance and asks god to choose which to use, so that all may proceed according to his plan.
var trinity = new Trinity(); trinity.instance.ReceivePrayers("Smite libtards"); // only god knows which reference he used to hear this 
Collusion
There is no Collude method in REPEL.
REPEL2.0 Proposals:
More Interrotations
Census - Generates a blacklist of data sources that match the given profile so they can be quickly processed in future interrogations.
Gerrymander - Sorts elements across a set of collections into a new set of collections where the maximum amount of them will match an expected result. If the process is unable to complete successfully, it repeats while excluding more non-conforming data on each subsequent iteration.
Poll - Runs a query at regularly scheduled intervals but only reports completion when the query results meet a given criteria.
Garbage Collection
Too socialist. Needs to be privatized.
Reflection
Numerous problems: Violates personal privacy, exposes weaknesses in controlling procedures, and leads to self-awareness.
Suggest wrapping in REPEL-friendly helpers that can enforce a) authority relationships between classes, and b) beliefs on self-reflection.
valueof()
Converts the time spent in a method into its bitcoin value.
submitted by 576274967 to ProgrammerHumor [link] [comments]

Linker error: Tap dance related... maybe?

Once again I shall come to you my dear sirs and madams for rescue! Finally everything complies but now the linker is acting up...
***userspace/rumlyne.c #include "quantum.h" #include "process_keycode/process_tap_dance.h" //#include "action_layer.h" #include "rumlyne.h" #include "nqadnw_basic_layout.h" --- ***userspace/rumlyne.h#pragma once #ifndef RUMLYNE_H #define RUMLYNE_H #include "keymap_german.h" #include  #include "quantum.h" #include "action.h" ---insert many many definitions and stuff that apparently works because it is tap dance functions that seems to bother the linker--- #ifdef TAP_DANCE_ENABLE enum /*tap_key*/ { QOT = 0, CUR, TLD, AT, PAR, SDO, APT, PCM, GUI, UCS, AF4, GTN, GTW, EML, BYE, BR1, //bracket 1,2,3,4 BR2, BR3, BR4, ARH, //arrow H,J,K,L ARJ, ARK, ARL }; #endif // TAP_DANCE_ENABLE enum userspace_layers { _BASE = 0, // Programmer BUX // default _JPNS, // 2 // Japanese Kana layout based on esrilles new stickney layout // TODO FUTURE _CODE, // 3 // Code friendly layer _STD, // 4 // QWERTZ, QWERTY, AZERTY, etc. _RAISE_L, // _RAISE when accessed via left MOD // BuT based symbol layer _RAISE_L_C, // _RAISE when accessed via left MOD on _CODE layer _RAISE_R, _RAISE_R_C, _LOWER_L, _LOWER_L_C, _LOWER_R, _LOWER_R_C, _LEFT, _LEFT_C, // _LEFT when pressed on _CODE layer _RIGHT // NUM+ // _RIGHT_C }; // NQADNW specific layer MODs #define RS_L LT(_RAISE_L, KC_SPC) // access _RAISE via left MOD #define RS_L_C LT(_RAISE_L_C, KC_SPC) // access _RAISE_C via left MOD on _CODE layer #define RS_R LT(_RAISE_R, KC_DOT) // access _RAISE via right MOD #define RS_R_C LT(_RAISE_R_C, KC_DOT) // access _RAISE_C via right MOD on _CODE layer #define LW_L LT(_LOWER_L, KC_COMM) // access _LOWER via left MOD #define LW_L_C LT(_LOWER_L_C, KC_COMM) // access _LOWER_C via left MOD on _CODE layer #define LW_R LT(_LOWER_R, KC_ENT) // access _LOWER via right MOD #define LW_R_C LT(_LOWER_L_C, KC_ENT) // access _LOWER_C via right MOD on _CODE layer #define LEFT TT(_LEFT) #define RIGHT LT(_RIGHT, /*TG(_RIGHT)*/KC_NO) // TODO FUTURE //#define CODE TT(_CODE) ---imsert many many definitions and stuff that apparently works because it is tap dance functions that seems to bother the linker--- // String keycodes & dynaminc macro dependancy enum more_custom_keycodes { DYNAMIC_MACRO_RANGE = NEW_SAFE_RANGE, // necessary for dynamic macros according to QMK guide KS_00, NEW_NEW_SAFE_RANGE }; char ST_EML_UNAME1[10] = "xxxxxxxxxx"; char ST_EML_UNAME2[17] = "xxxxxxxxxxxxxxxxx"; char ST_EML_UNAME3[7] = "rumlyne"; // :) char ST_EML_DOMAIN1[9] = "xxxxxxxxx"; char ST_EML_DOMAIN2[6] = "xxxxxx"; char ST_EML_DOMAIN3[6] = "xxxxxx"; char ST_EML_DOMAIN4[6] = "xxxxxx"; char ST_DNUL[2] = "00"; char ST_SUDO[5] = "sudo "; char ST_DFNE[8] = "#define "; char ST_INCL[9] = "#include "; char ST_APIS[16] = "apt-get install "; char ST_APUD[15] = "apt-get update "; char ST_APUG[16] = "apt-get upgrade "; char ST_PMNS[10] = "pacman -S "; char ST_PSYU[12] = "pacman -Syu "; char ST_PSYY[14] = "pacman -Syyuu "; static const char ST_SGDH[31] = {"Sehr geehrte Damen und Herren, "}; static const char ST_LKUK[32] = {"Liebe Kolleginnen und Kollegen, "}; static const char ST_MFG1[20] = {"Mit freundlichen Gr["}; // siehe quantum/keymap_extras/sendstring_german char ST_MFG2[2] = "n "; char ST_HAVL[17] = "Hochachtungsvoll "; char ST_DSOM[19] = "Dear sir or madam, "; char ST_DRCS[16] = "Dear collegues, "; char ST_BTRS[14] = "Best regards, "; /* static const char * const ST_DEGR[31] = { "Sehr geehrte Damen und Herren, ", "Liebe Kolleginnen und Kollegen, ", "Mit freundlichen Grüßen " }; */ #ifdef UNICODE_ENABLE enum unicode_name { //UST_HBR, // //UST_DEG, // //UST_LIR, // UST_BIT, // ₿ Bitcoin //UST_EUR, // € UST_BPN, // £ UST_YEN, // ¥ UST_TMK, // ™ UST_RTM, // ® UST_CPR // © }; const uint16_t PROGMEM unicode_map[] = { //16 genug? //[UST_HBR] = 0x0127, //[UST_DEG] = 0x00B0, //[UST_LIR] = 0x20BA, [UST_BIT] = 0x20BF, // ₿ Bitcoin //[UST_EUR] = 0x20AC, // € [UST_BPN] = 0x00A3, // £ [UST_YEN] = 0x00A5, // ¥ [UST_TMK] = 0x2122, // ™ [UST_RTM] = 0x00B0, // ® [UST_CPR] = 0x00AE // © }; #endif // UNICODE_ENABLE bool process_record_user(uint16_t keycode, keyrecord_t *record) { // send strings, send even more strings when tap dance is disabled switch(keycode) { case KS_00: if (record->event.pressed) { send_string(ST_DNUL); return false; } } return true; }; // Tap dance events // ' " void td_quot_dqot (qk_tap_dance_state_t *state, void *user_data) { if (state->count == 1) { clear_mods(); //tap_code(DE_QUOT); register_code(KC_LSFT); tap_code(KC_BSLS/*DE_HASH*/); unregister_code(KC_LSFT); } else if (state->count == 2) { clear_mods(); //tap_code(DE_DQOT); register_code(KC_LSFT); tap_code(KC_2); unregister_code(KC_LSFT); } else if (state->count == 3) { clear_mods(); //tap_code(DE_DQOT); //tap_code(DE_DQOT); register_code(KC_LSFT); tap_code(KC_2); tap_code(KC_2); unregister_code(KC_LSFT); tap_code(KC_LEFT); } else if (state->count == 4) { clear_mods(); //tap_code(DE_QUOT); //tap_code(DE_QUOT); register_code(KC_LSFT); tap_code(KC_BSLS/*DE_HASH*/); tap_code(KC_BSLS/*DE_HASH*/); unregister_code(KC_LSFT); tap_code(KC_LEFT); } else if (state->count >= 5) { reset_tap_dance(state); } reset_tap_dance(state); }---And so on--- qk_tap_dance_action_t tap_dance_actions[] = { [QOT] = ACTION_TAP_DANCE_FN(td_quot_dqot), ---and so on--- }; #endif // rumlyne.h 
With make idobo:rumlyne it successfully compiles everything until shit hits the fan when it the linker engages:
Compiling: users/rumlyne/rumlyne.c [OK] Compiling: keyboards/idobo/keymaps/rumlyne/keymap.c [OK] Linking: .build/idobo_rumlyne.elf [ERRORS] | | .build/obj_idobo_rumlyne/keyboards/idobo/keymaps/rumlyne/keymap.o (symbol from plugin): In function `td_quot_dqot': | (.text+0x0): multiple definition of `td_quot_dqot' | .build/obj_idobo_rumlyne/rumlyne.o (symbol from plugin):(.text+0x0): first defined here ---and so on---- | .build/obj_idobo_rumlyne/rumlyne.o (symbol from plugin):(.text+0x0): first defined here | .build/obj_idobo_rumlyne/keyboards/idobo/keymaps/rumlyne/keymap.o (symbol from plugin): In function `td_quot_dqot': | (.text+0x0): multiple definition of `unicode_map' | .build/obj_idobo_rumlyne/rumlyne.o (symbol from plugin):(.text+0x0): first defined here | .build/obj_idobo_rumlyne/keyboards/idobo/keymaps/rumlyne/keymap.o (symbol from plugin): In function `td_quot_dqot': | (.text+0x0): multiple definition of `ascii_to_keycode_lut' | .build/obj_idobo_rumlyne/rumlyne.o (symbol from plugin):(.text+0x0): first defined here | .build/obj_idobo_rumlyne/keyboards/idobo/keymaps/rumlyne/keymap.o (symbol from plugin): In function `td_quot_dqot': | (.text+0x0): multiple definition of `ascii_to_shift_lut' | .build/obj_idobo_rumlyne/rumlyne.o (symbol from plugin):(.text+0x0): first defined here | collect2.exe: error: ld returned 1 exit status | make[1]: *** [tmk_core/rules.mk:299: .build/idobo_rumlyne.elf] Errors 1 Make finished with errors make: *** [Makefile:544: idobo:rumlyne] Errors 1 
I have no idea what this is about and a quick google search didn't reveal much. Let me know if you need to see the other headers/full config/.build folder.

Edit: compiling in a newly installed instance of msys on win7.
Edit2: Here and here are the links to github
Edit3 2019-02-05: by using static const char when defining my "strings" I got the linker errors down to the last 2 parts regarding ascii_to_keycode_lut & ascii_to_shift_lut which are a result of including . Without it it compiles but of course the "strings" sent will be incorrect.

submitted by rumlyne to olkb [link] [comments]

Colored Coins Idea

Let's say a token is associated with a fresh bitcoin address. The creator makes an OP_RETURN transaction to it with data which has this format:
[string: CCIDENTIFIER][uint: VERSION][string: NAME][uint: MAX_COINS][bool: AUTOMATIC]
Where CCIDENTIFIER is some string that means colored coin format, VERSION is version of colored coin, NAME is name of token, MAX_COINS is total valid tokens to create, AUTOMATIC to send all coins to creator, otherwise see below.
After this is created, the creators address is the first owner of the MAX_COINS. Alternatively there could be something else in place for spreading this between multiple addresses, but let's keep it simple for now :) (such as creator making special transactions to spread out between multiple addresses or something)
A modified wallet would index and store all transactions to and from the token address. So you would add the token address to be watched in the ui, and it would show the name and track balances / utxo set of this token associated with your other addresses.
Your special wallet would also need to implement transactions. To transact with this colored coin you'd need to make a special type of transaction to the tokens address which would include:
Nodes for this colored coin could validate and see if it was legitimate or not and update the balances between addresses. Every user which is running the special node could validate and check the complete history for all the transactions of this colored coin by just following the transactions involving this single address. Really all you'd need to do would be to store the utxo set of the colored coin to keep in sync. If invalid transactions are encountered they'd just be skipped. The ruleset is pretty simple (check utxo for owner has enough tokens, if so transaction is valid).
submitted by t_bptm to btc [link] [comments]

GAW Miners - Liars, Frauds - A brief recap of what we know.

EDIT: I was asked by a GAW staff member to compile a list of questions the community has with/about GAW, Paybase, etc. Please provide any questions you have below and I'll have them forwarded
EDIT 2: It seems Josh is working on answering the questions I've asked and compiled. We'll see what happens when answers are released.
Hello, in the midst of this public uprising against GAW I'd like to present some facts for those of you who either:
a. Don't know who/what "GAW" is and why they're a scam,
b. Are brainwashed by Garza; those of you who genuinely believe in Paycoin and GAW Miners,
c. Don't quite have all of the information.
Note that I don't have every possible snippet of information out there, I'll just bring up some of the main points and complaints.
Pre-GAW
Ten months ago Garza was first introduced to the Bitcoin community in this post and this post.. From these posts we learn quite a bit of information regarding Garza's past; he offered false business deals to eBay sellers to partner with him. In the first article, we see that after he offered this couple "20% of his total profit" from his mining company and the couple asked for a reasonable counter-offer of $5k/month to pay their bills since they were unemployed, Garza filed a false Significantly Not As Described case on eBay, causing the couple to quite a bit of money and seriously affected their finances. The couple did some research about Garza and found this:
After looking at their old facebook profile, we saw that they were originally DirectTV salesman preying on small rural towns around New England offering people high-speed, internet and other telecom services that these people weren't able to get for whatever reason before. GAW was able to coerce MBI (Massachusetts Broadband Institute) to donate $40,000 to them for helping to bring services to everyone in the communities. Garza promised to build towers and other bullshit in these towns to help provide services, but they never did. At some point even when community leaders (one was David Kulp) repeatedly tried to get in touch with them, they never heard back.
So, it seems Garza has a knack for deceptive practices 'eh? Since the posts are so long and there's a lot to discuss, I'll let you read them and formulate your opinion on Garza. (Thanks to DidHeJust for the links to those threads).
-Early Phases
Originally, GAW showed NO proof of mining at all (not an address, block, pictures of mining hardware, pool usernames, nothing). Later on, during the Hashpoint 'mining' phase, he purchased 5 PH/s worth of mining equipment from Bitmaintech. For the short amount of time Paycoin was available for proof-of-work mining, there were tons of people renting mining rigs in order to get a cut of the "$20 Paycoins." Since the difficulty was fairly low, the prices per TH/s of these miners were very high, making it extremely easy to ROI on them. I'd be willing to bet that GAW rented out a lot of their hashpower for profit. They're currently selling the hardware they have left from this on oneminer.com.
There was also a brief period of time where you were able to purchase hardware from GAW and have it point to a pool of your choosing; however, this didn't account for too large of a portion of the hashpower they claim to have sold.
-Forums
GAW Miners owns a forum created them them, Hashtalk. This forum is heavily censored; if you attempt to inquire about some of GAW's deceptive practices, broken promises, or Paycoin design you'll either be outright banned or shadow banned (your account will remain useable to you, but nobody will be able to see any of your posts). This led to this uncensored discussion thread on Bitcointalk.
- Broken Promises
Promise 1: *"Always Profitable"**
GAW Miners claims that their Hashlets would always remain profitable and the $0.08 fee per MH/s would go down overtime. You know what GAW did instead? They kept their fees the same even when people were receiving only 1 satoshi. That's hardly profitable at all, as it's the minimum amount that they can really pay. So, they decided to move to mining Hashpoints for Paycoin (another broken promise, explained later).
Promise 2: *"Paycoin would launch with a $20 floor"**
This one is interesting. For the three months or so Hashpoint mining was available, Garza claimed that Paycoin would have a $20 floor (essentially that GAW would buy up any coin sold below $20 to keep the market place there or higher). Now, however, they've purged their censored forum of such claims so all that remains are screenshots as proof. Here's a few: https://i.imgur.com/YFXJiKB.png and https://i.imgur.com/HnotyMB.png Paycoin was traded at about $20 for a very brief period of time, but since then it's been dropping steadily, trading at just above $6/ea currently. Garza has done nothing to rectify the situation since.
Promise 3: *Large merchant support on launch**
From this thread we see that Garza promises that:
That’s right, you will be able to shop with Paycoin on the Amazon, Target, Walmart, Macy*s and Best Buy’s online stores.
A journalism website, coinfire.cf, contacted Amazon and the other companies claimed to be partnered with GAW. These companies all denied being affiliated with GAW, Amazon even threatened legal action if this continued. Once the article was published, the coinfire website was mysteriously hacked and the day after GAW threatened legal action. Read more about it here:
https://coinfire.cf/2014/11/22/is-gaw-miners-lying-about-partnerships/ and http://www.scribd.com/doc/248372603/Coinfire-Cease-and-Desist
-Censorship [Developing!!!]
At the moment GAW is taking down videos they've posted where they've made a certain "statement" on their mining.
-Paycoin
Ah, Paycoin. An altcoin plagued by delays and broken promises. Originally set to launch at $20 per coin, falsely leading people into investing money into Hashpoint miners for profit. The things Josh is doing and has done to get people to use Paycoin are laughable, I'd consider it treason against the Bitcoin community. He purchased the domain btc.com for $1,000,000 only to have it redirect to Paybase. Fun stuff 'eh? He's also claimed that his coin would be better than Bitcoin, denouncing it in order to promote his own coin. From code snippets we've seen, Paycoin's "Prime Nodes," part of the PoS system to generate new coins, has the ability to generate coins at a 350% interest rate. These wallets/stakers/controllers/nodes are only able to be controlled by GAW, of course. The code:
int64 nSubsidy = 0; int64 nRewardCoinYear = 0; // creation amount per coin-year if (primeNodeRate == 0) nRewardCoinYear = 5 * CENT; else if (primeNodeRate == 10) nRewardCoinYear = 10 * CENT; else if (primeNodeRate == 20) nRewardCoinYear = 20 * CENT; else if (primeNodeRate == 100) nRewardCoinYear = 100 * CENT; else if (primeNodeRate == 350) nRewardCoinYear = 350 * CENT; nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8); if (fDebug && GetBoolArg("-printcreation")) printf("GetProofOfStakeReward(): primeNodeRate=%d create=%s nCoinAge=%"PRI64d"\n", primeNodeRate, FormatMoney(nSubsidy).c_str(), nCoinAge); return nSubsidy; 
Paycoin started off as a coin with a 13,000,000 coin market cap, with two stages. A Proof of Work and Proof of Share. Check this out: https://twitter.com/gawceo/status/532173907718332417 - Garza claims that he "mined" for the 12,000,000 coins he gained, although block one was programmed to give him that much... hah!
Credits to https://gist.github.com/jyap808/3f99de084df18ce325a7 for this;
Block 1. 12 million premine.
343,196 XPY mined during Proof of Work period.
343,196 - 56,889 = 286,307 XPY not mined by GAW Miners
12,343,196 XPY coins mined Total at the end of Proof of Work including pre-mine.
100 - (343196.0 / 12343196 * 100) = 97.22% Premined at the end of Proof of Work
It also seems like Garza stole the logo for Paycoin from https://www.gopago.com/. If you compare it with what's on https://paybase.com/ they're identical.
-Current and Recent Events
It's also known that there was a massive security/data breech during the Paybase launch, which allowed users to see other's balances and personal information https://coinfire.cf/2014/12/31/massive-security-breach-at-paybase/ which is being blamed on a "Cloudflare Caching Issue," however, that excuse makes very little sense.
Currently, people are having trouble withdrawing their Paycoins from Paybase, which GAW is blaming on Authy. Authy's services are functioning fine for all other services, which leads us to believe that it isn't Authy's fault.
When Hashtakers were sold, they would've only been really profitable at the $20 per Paycoin mark. With the current price people are losing money on their investment.
Note: This is somewhat unfinished and I'd like to hear feedback on what I should add and revise.
submitted by iTipBitcoin to Bitcoin [link] [comments]

goodAccountingPump

pragma solidity ^0.4.24; contract StakeableTokenABI { function goodAccounting( address _staker, uint256 _stakeIndex ) external ; struct StakeStruct { uint256 amount; uint256 shares; uint256 lockTime; uint256 endStakeCommitTime; uint256 periods; bool isInGlobalPool; uint256 timeRemovedFromGlobalPool; uint256 latePenaltyAlreadyPooled; } mapping(address => StakeStruct[]) public staked; } contract goodAccountingPump { StakeableTokenABI public h; // bitcoin hex contract address mapping(address => uint256) public funds; mapping(address => uint256) public reward; constructor(StakeableTokenABI _hex) public { h = _hex; } function getReward( address _staker, uint256 _stakeIndex) public view returns(uint256) { (,,,uint256 endStakeCommitTime,,bool isInGlobalPool,,) = h.staked(_staker,_stakeIndex); if(isInGlobalPool && block.timestamp > endStakeCommitTime) { if(funds[_staker] >= reward[_staker]) return reward[_staker]; return funds[_staker]; } return 0; } function goodAccounting( address _staker, uint256 _stakeIndex ) public { (,,,uint256 endStakeCommitTime,,bool isInGlobalPool,,) = h.staked(_staker,_stakeIndex); if(isInGlobalPool && block.timestamp > endStakeCommitTime) { h.goodAccounting(_staker,_stakeIndex); uint256 payment = getReward(_staker,_stakeIndex); if(payment > 0) { funds[_staker] -= payment; msg.sender.transfer(payment); } } } function addfunds(uint256 _reward) public payable { funds[msg.sender] += msg.value; reward[msg.sender] = _reward; } } 
This code is untested and should not be used as it will most likely contain logic errors. I am posting it just to express an idea and coding helps me think about whats possible. Anyway the idea is that this contract calls the good accounting function on the bitcoin hex contract and pays the caller with an amount specified by whoever pays into it. Multiple users can fund it and set their own individual rewards for calling the accounting function on their address. The contract checks to see if the stake is in the global pool and matured otherwise it wont let the caller be rewarded.
Would this be the right condition to pay callers?
submitted by utxohodler to BitcoinHEX [link] [comments]

COINBASE Inc. applies for 9 patents including: Bitcoin exchange, Tip Button, or Hot Wallet. WTF?

As readed here: http://cointelegraph.com/news/115316/bank-of-americas-and-coinbases-bitcoin-patents-revealed
Coinbase Inc.:
20150262176, “Hot Wallet For Holding Bitcoin”; 20150262172, “User Private Key Control”; 20150262171, “Bitcoin Private Key Splitting For Cold Storage” 20150262168, “Instant Exchange”; 20150262141, “Personal Vault”; 20150262140, “Send Bitcoin To Email Address”; 20150262139, “Bitcoin Exchange”; 20150262138, “Tip Button”; 20150262137, “Off-Block Chain Transactions In Combination With On-Block Chain Transactions.” 
http://appft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&p=1&u=%2Fnetahtml%2FPTO%2Fsearch-bool.html&r=0&f=S&l=50&TERM1=Coinbase&FIELD1=AS&co1=OR&TERM2=Cite+Brian+Cohen+or+CoinTelegraph+%28Esquivalience%29&FIELD2=DRTX%2CDETD&d=PG01
Or maybe I'm just missunderstanding: " The invention provides a host computer system for transacting bitcoin including a processor, a network interface device connected to the processor, a computer readable medium connected to the processor, a data store on the computer readable medium and a set of instructions on the computer readable medium that are executable by the processor. "
submitted by atleticofa to Bitcoin [link] [comments]

#For Review: 'Intrinsically Tradable Tokens' (ITT's) are their own exchange

For Review: 'Intrinsically Tradable Tokens' (ITT's) are their own exchange

Introducing Intrinsically Tradable Tokens, ERC20 compliant tokens in which you can buy and sell directly from the contract.
Ropsten 0xa9e001bebe4b281f7229b0305f553ab3c511fef5
Live 0xa15c784319fa96d3E36cFE97fbadD89Ec704A8dc

ITT's extend the ERC20 API with:

buy(uint price, uint amount, bool make) sell(uint price, uint amount, bool make) cancel(uint price) withdraw(uint ether) 
and other ancillary exchange state getters (see Github repo for full API) such as :
etherBalanceOf(address holder) getBook() getOrdersOf(address trader) spread(bool side) 
The intrinsic exchange functionality works on a FIFO matching maketaker algorithm. A new order may be iteratively filled by multiple make orders on the book or if unfilled, can be put on the book itself as a make order.
ITT demo contracts have been deployed on the Ropsten test chain on which a number of Buy and Sell orders have already been placed for you to play with. The demo ITT and future, more functional ITT's can be can be interacted with using the front end DAPP ITTDesk.

Use Cases

This demo ITT serves to demonstrate the exchange functionality of a basic ITT contract and does not have much intrinsic value in the token itself beyond being a purely speculative coin.
The ITT API and base contract are open source and offered to the community in order to extend or attach value adding functionality to the token side.
As is, crowd funding and token sales become as trivial by simply placing ask orders (see Self Funding below).
Better still would be to extended ITT functionality to make a 'Payable ITT' which becomes a simple but highly versatile pay to an unknown many mechanism which can distribute payments according to proportional holdings. Such holdings might represent shareholders, a rewards system or perhaps be used to fund and manage a DAO's project funds. (I do have a Payable ITT but will not likely release it until the community has confidence in the basic ITT contract)
Other value adding developments might be to couple ITT's to fiat currencies for truly low friction decentralised forex.

Current State of Development

As deployed, the ITT Demo contract is yet to undergo extensive testing and formal verification. It appears to work as intended (unless compiled with 0.4.5+commit.b318366e! My first launch attempt drove me crazy until that bug was announced). The contract on both chains have been verified on etherscan.io etherscan.io.
The ITTDesk app is very much in alpha release, minimalist and clunky in it's function. It is written on Meteor and attempts to use Mist styling and elements. Probably best just to clone the repo and run it up in Meteor at this stage. It features intelligent ask/bid/buy/sell trade buttons to assisting in validating user inputs in the order fields.
I am not an experienced web developer, so feed back, suggestions, criticisms are most welcome. In particular, I've not been able to work up the filters without causing browser timeout.

How does it work?

The order book utilises a mapping of 'Circular Linked Lists (CLL)' from the LibCLLi library to order and lookup the booked prices and iterate the FIFO's at each price. Each FIFO in the mapping is keyed by its price and holds all the addresses of traders who have made orders at that price. A trader can only have a single order at any particular price. An attempt to book another order at the same price will adjust and put the order at the back of the FIFO queue. This prevents FIFO hogging in which a trader might otherwise starve other orders by continually topping up their own.
A second trivial mapping holds the actual order amounts. It is keyed by a SHA3 hash of the trader's address with the price of the order (and is actually what limits the trader to one price, one order).
The CLL's heads are static at mapping key '0'. To use as a FIFO, nodes are simply inserted previous to the head and removed from next to the head. A FILO (stack) can be implemented with equal simplicity.
In the case of the price list, the links either side of the head are the highestBid (previous) and lowestAsk (next) making the head node itself the market spread. The price list is artificially bound to minimum (uint 1) and maximum (uint 2**128) prices. New price nodes are inserted relative to the head (spread) after iterating through an order search.
Looping operations in Smart Contracts can be bug prone and costly, especially with state mutations in each loop as in the ITT's matching algorithm. For this reason, the order matching loop is dynamically limited by the gas supply from msg.gas and will exit with a partially filled order rather than throw it. The remainder does not get put on the book as a make order as it would cause a bid/ask collision at that price. Because of this looping, gas cannot be estimated and it is up to the trader to consider the costs and adjust the amount of gas prior to ordering.
The matching algorithm is not without architectural efficiency however which almost halves the number to calls to STORE by virtualising (caching to memory) the taker's state variables prior to the matching loop and writing back to store once the matching and making operations exit.

Security and Resilience

ITT's hold ether balances and therefore are presumed to be targeted by hacking attempts. A number of security features and practices have therefore been programmed into the contract.
All external or payable state mutating functions are 'reentry protected' by a mutex which is set and cleared in the internal function safeSend(), which is called only by the public function withdraw(). This practice ensures a single entry and exit.
The architecture also separates entry validation logic and parameter preparation which is kept in the external/payable functions, from state mutation logic which is kept in the internal functions. This allows for a secure, flexible, inheritable API/interface layer from which to extend the contract while keeping the basic ITT internal functionality the same.
In the ITT Demo, the default function is unimplemented and therefore throws if payments are sent to anything other than the payable buy() function.
Attention must also be drawn to some rather unconventional use of uint math in the matching loop. Elsewhere, the contract uses explicitly safe maths functions, however the nature of an exchange function requires numerous inverse and signed integer operations. It was found that casting between int and uint became an onerous task with potentially unpredictable outcome and a design decision was made to simply treat uint as signed within the matching loop. In this case -1 == 2**256-1 and is used in multiplication to change the sign of trade amounts during matching.
In light of the signed uint adoption, a further mathematical constraint was placed on the maximum price and amount allowed being 2**128 which prevents any multiplication overflows.

Testing

Given that this contract is Proof of Concept deployment primarily for public review, it should be considered insecure. It has been tested for functionality but no exhaustive testing regime or formal verification has been put against it. It is undeniably a big ugly contract with complex logic and so should be viewed with suspicion.
Interacting with the Live contract is thereby at your own risk!

Self Funding

Being the deploying owner of this Demo ITT, I am granted the full balance of tokens and have placed both ask and bid orders as examples. Purchasing my Ask orders on the Live chain does transfer real ether to my balance and so I am trailing this as a channel for funding my development efforts rather than chasing bounties, competitions, donations, (a real job) or what have you. If you buy tokens here, you could consider it as a much appreciated donation which you might also be able to return a speculative profit from! It would certainly make my life easier. :)

Who Am I?

My name is Darryl Morris AKA o0ragman0o. I'm an independent (and some what isolated) Australian Ethereum developer. Though fairly quite, I've been following Ethereum developments since November 2014 (PoC 6) and have been small time mining since Olympic, though not now with expensive Australian electricity. I am best known on [forum.ethereum.org](forum.ethereum.org) where I am a mod. I've been crypto aware since 2009 when I tried bitcoin in it's infancy. I got 71/70 marks for Griff Green's notorious 'DAO Ninja' homework though obviously needed 72 to recognise the complex of vulnerabilities in that code!
My interests are in developing delegative democracy technologies with which to render all politicians obsolete (particularly ones beginning with 'T'). To that end I've developed the ITT contract as a funding component of a democracy DAO framework I call 'Ethenian DAO'.
Looking for interested collaborators.
Cheers Darryl
submitted by o0ragman0o to ethereum [link] [comments]

WOW!! YES, VERY COOL BITCOIN CHARTS BUT THIS BITCOIN ... C-BooL - Catch You (Official Video) - YouTube How to mine $1,000,000 of Bitcoin using just a laptop ... BITCOIN AUSBRUCH STEHT KURZ BEVOR!!! - YouTube High Limit Coin Pusher full of Bitcoins! I came out a ...

Der Bitcoin nimmt nach der Korrektur auf unter 9.000 Dollar wieder Fahrt auf. Für positive fundamentale Impulse sorgt mal wieder PayPal. Denn die Pläne des Payment-Giganten, Bitcoin in sein ... Bitcoin Core integration/staging tree. Contribute to bitcoin/bitcoin development by creating an account on GitHub. Bitcoin Core integration/staging tree. Contribute to bitcoin/bitcoin development by creating an account on GitHub. Wissenswertes über Bitcoins Unser Bitcoin Chart zeigt Ihnen den aktuellen Bitcoin Kurs in Euro (Kürzel: BTC und XBT) sowie die Bitcoin Kursentwicklung (Bitcoincharts).Wenn Sie Bitcoins kaufen möchten, können Sie sich hier anmelden.In unseren Bitcoin.de FAQs und in unserem Tutorial "Mein erster Bitcoin" erfahren Sie, wie Sie Bitcoins verkaufen oder kaufen können. The Bitcoin.com mining pool has the lowest share reject rate (0.15%) we've ever seen. Other pools have over 0.30% rejected shares. Furthermore, the Bitcoin.com pool has a super responsive and reliable support team.

[index] [11087] [6769] [15892] [23091] [10579] [42985] [49770] [37066] [43497] [49819]

WOW!! YES, VERY COOL BITCOIN CHARTS BUT THIS BITCOIN ...

Download or Stream links here: http://soundline.biz/CBooLCatchYou C-BooL Instagram: https://www.instagram.com/c_bool/ C-BooL Facebook: http://bit.ly/1SV9tk3 ... In todays video we take a look at the Bitcoin price but more important I am going to share The bitcoin family prime Machina with you all. the Landrover disco... http://bitcoin-informant.de/2019/02/28/562-bitcoin-reservewaehrung-der-welt-nutzerdaten-auf-der-blockchain-bitcoin-wale-stocken-auf Hey Krypto Fans, willkomm... Todays Video I find Coin Pusher Full Of Bitcoins! Each coin is chance to win actually Bitcoin Cryptocurrency! Check out E-Win athttps://bit.ly/2tHQPwB and 30... Bybit bis zu $390 Bonus: https://www.bybit.com/app/register?ref=RPyME Bybit Tutorial: https://www.youtube.com/watch?v=k0MWynMHUF8&t= 👇🏻Unterstütze den Kana...

#