Elogio a 'Mastering Bitcoin'

Размер: px
Начинать показ со страницы:

Download "Elogio a 'Mastering Bitcoin'"

Транскрипт

1 Elogio a 'Mastering Bitcoin' "Quando parlo di bitcoin a un pubblico generico, mi chiedono qualche volta 'ma come funziona in sostanza?' Ora ho un ottima risposta a quella domanda, perchè chiunche legga Mastering Bitcoin avrà una profonda conoscenza di come funziona e sarà ben equipaggiato per scrivere la prossima generazione di sorprendenti applicazioni sulle cryptovalute." Gavin Andresen, Chief Scientist della Bitcoin Foundation "Bitcoin e le tecnologie blockchain stanno diventando i mattoni per l internet di nuova generazione. I migliori e i più brillanti della Silicon Valley stanno lavorando su di esse. Il libro di Andreas vi aiuterà a partecipare nella rivoluzione software che stà avvenendo nel mondo della finanza" Co-founder AngelList Mastering Bitcoin è la migliore referenza tecnica disponibile ad oggi su bitcoin. E bitcoin diventerà presto, molto probabilmente, la più importante tecnologia di questa decade. Come tale, questo libro è assolutamente da avere per ogni programmatore e sviluppatore software, specialmente quelli interessati nel creare applicazioni con il protocollo bitcoin. Assolutamente consigliato." General Partner, Andreessen Horowitz L invenzione della Blockchain Bitcoin rappresenta una piattaforma completamente nuova su cui costruire, una che abiliterà un ecosistema così ampio e diversificato come internet stesso. Come uno dei più preminenti leader del pensiero che sta attorno a bitcoin, Andreas Antonopolous è la scelta perfetta per un libro del genere." Bitcoin Entrepreneur and Investor 1

2 Indice

3 Prefazione Scrivere il Bitcoin Book I first stumbled upon bitcoin in mid My immediate reaction was more or less "Pfft! Nerd money!" and I ignored it for another six months, failing to grasp its importance. This is a reaction that I have seen repeated among many of the smartest people I know, which gives me some consolation. The second time I came across bitcoin, in a mailing list discussion, I decided to read the white paper written by Satoshi Nakamoto, to study the authoritative source and see what it was all about. I still remember the moment I finished reading those nine pages, when I realized that bitcoin was not simply a digital currency, but a network of trust that could also provide the basis for so much more than just currencies. The realization that "this isn t money, it s a decentralized trust network," started me on a four-month journey to devour every scrap of information about bitcoin I could find. I became obsessed and enthralled, spending 12 or more hours each day glued to a screen, reading, writing, coding, and learning as much as I could. I emerged from this state of fugue, more than 20 pounds lighter from lack of consistent meals, determined to dedicate myself to working on bitcoin. Two years later, after creating a number of small startups to explore various bitcoin-related services and products, I decided that it was time to write my first book. Bitcoin was the topic that had driven me into a frenzy of creativity and consumed my thoughts; it was the most exciting technology I had encountered since the Internet. It was now time to share my passion about this amazing technology with a broader audience. Pubblico di Riferimento This book is mostly intended for coders. If you can use a programming language, this book will teach you how cryptographic currencies work, how to use them, and how to develop software that works with them. The first few chapters are also suitable as an in-depth introduction to bitcoin for noncoders those trying to understand the inner workings of bitcoin and cryptocurrencies. Convenzioni usate in questo libro Le seguenti convenzioni tipografiche sono usate in questo libro: Italic Indica nuovi termini, URLs, indirizzi , filename, e estensioni. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. 1

4 Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP L icona sta a significare un tip, un suggerimento o una nota generale. Questa icona indica un avvertimento o cautela. Esempi di Codice Gli esempi sono illustrati in Python, C++, e usando la riga di comando di un sistema operativo Unix-like come Linux o Mac OS X. Tutti i frammenti di codice sono disponibili nel repository GitHub nella directory code del repo principale. Fai un fork del codice del libro, prova gli esempi di codice o sottoponi delle correzioni via GitHub. Tutti i frammenti di codice possono essere replicati in gran parte dei sistemi operativi con un installazione minimale di compilatori e interpreti per i rispettivi linguaggi. Dove necessario, forniamo istruzioni d installazione basilari ed esempi passo-passo dell output di quelle istruzioni. Alcuni dei frammenti di codice e degli output sono stati riformattati per la stampa. In tutti questi casi le linee sono state divise da una barra rovesciata (\), seguita da un carattere newline. Quando si trascrivono gli esempi si rimuovano questi due caratteri e si uniscano di nuovo le linee; si dovrebbero vedere risultati identici a quelli nell esempio. Tutti i frammenti di codice usano dove possibile valori reali e calcoli, in modo che si possa costruire di esempio in esempio e vedere gli stessi risultati in ogni codice si scriva per calcolare gli stessi valori. Per esempio, le chiavi private e le corrispondenti chiavi pubbliche e indirizzi sono tutti reali. Le transazioni di prova, i blocchi, e i riferimenti in blockchain sono stati tutti introdotti nella reale catena dei blocchi bitcoin e sono parte del registro pubblico; dunque si possono consultare in qualsiasi sistema bitcoin. Riconoscimenti Questo libro rappresenta gli sforzi e i contributi di molte persone. Sono grato per tutto l aiuto che ho ricevuto da amici, colleghi ed anche sconosciuti, che si sono uniti in questo sforzo per scrivere il libro tecnico definitivo su cryptocurrencies e bitcoin. It is impossible to make a distinction between the bitcoin technology and the bitcoin community, and this book is as much a product of that community as it is a book on the technology. My work on this book was encouraged, cheered on, supported, and rewarded by the entire bitcoin community from the very beginning until the very end. More than anything, this book has allowed me to be part of a 2

5 wonderful community for two years and I can t thank you enough for accepting me into this community. There are far too many people to mention by name people I ve met at conferences, events, seminars, meetups, pizza gatherings, and small private gatherings, as well as many who communicated with me by Twitter, on reddit, on bitcointalk.org, and on GitHub who have had an impact on this book. Every idea, analogy, question, answer, and explanation you find in this book was at some point inspired, tested, or improved through my interactions with the community. Thank you all for your support; without you this book would not have happened. I am forever grateful. The journey to becoming an author starts long before the first book, of course. My first language (and schooling) was Greek, so I had to take a remedial English writing course in my first year of university. I owe thanks to Diana Kordas, my English writing teacher, who helped me build confidence and skills that year. Later, as a professional, I developed my technical writing skills on the topic of data centers, writing for Network World magazine. I owe thanks to John Dix and John Gallant, who gave me my first writing job as a columnist at Network World and to my editor Michael Cooney and my colleague Johna Till Johnson who edited my columns and made them fit for publication. Writing 500 words a week for four years gave me enough experience to eventually consider becoming an author. Thanks to Jean de Vera for her early encouragement to become an author and for always believing and insisting that I had a book in me. Thanks also to those who supported me when I submitted my book proposal to O Reilly, by providing references and reviewing the proposal. Specifically, thanks to John Gallant, Gregory Ness, Richard Stiennon, Joel Snyder, Adam B. Levine, Sandra Gittlen, John Dix, Johna Till Johnson, Roger Ver, and Jon Matonis. Special thanks to Richard Kagan and Tymon Mattoszko, who reviewed early versions of the proposal and Matthew Owain Taylor, who copyedited the proposal. Thanks to Cricket Liu, author of the O Reilly title DNS and BIND, who introduced me to O Reilly. Thanks also to Michael Loukides and Allyson MacDonald at O Reilly, who worked for months to help make this book happen. Allyson was especially patient when deadlines were missed and deliverables delayed as life intervened in our planned schedule. The first few drafts of the first few chapters were the hardest, because bitcoin is a difficult subject to unravel. Every time I pulled on one thread of the bitcoin technology, I had to pull in the whole thing. I repeatedly got stuck and a bit despondent as I struggled to make the topic easy to understand and create a narrative around such a dense technical subject. Eventually, I decided to tell the story of bitcoin through the stories of the people using bitcoin and the whole book became a lot easier to write. I owe thanks to my friend and mentor, Richard Kagan, who helped me unravel the story and get past the moments of writer s block, and Pamela Morgan, who reviewed early drafts of each chapter and asked the hard questions to make them better. Also, thanks to the developers of the San Francisco Bitcoin Developers Meetup group and Taariq Lewis, the group s co-founder, for helping to test the early material. During the development of the book, I made early drafts available on GitHub and invited public comments. More than a hundred comments, suggestions, corrections, and contributions were submitted in response. Those contributions are explicitly acknowledged, with my thanks, in Bozza della Early Release (Contributi da GitHub). Special thanks to Minh T. Nguyen, who volunteered to manage the GitHub contributions and added many significant contributions himself. Thanks also to 3

6 Andrew Naugler for infographic design. Quando il libro era nella fase di bozza, è passato attraverso molti round di revisione tecnica. Grazie a Cricket Liu e a Lorne Lantz per la loro revisione approfondita, commenti e supporto. Molti sviluppatori bitcoin hanno contribuito ad esempi di codice, recensioni, commenti e incoraggiamenti. Grazie a Amir Taaki e Eric Voskuil per snippet di codice esempio e per i molti commenti di pregio; Vitalik Buterin e Richard Kiss per aver aiutato con la matematica della curva ellittica e altre contribuzioni al codice; a Gavin Andresen per correzioni, commenti e per l incoraggiamento; a Michalis Kargakis per i commenti, contribuzioni e per lo scritto su btcd; e a Robin Inge per le correzioni degli errori che hanno migliorato la seconda edizione; Devo tutto l amore che ho per le parole e per i libri a mia madre, Theresa, che mi ha cresciuto in una casa con libri che potevi trovare a ogni parete. Mia madre mi ha inoltre comprato il mio primo computer nel 1982, anche se si considera una che ha un po paura della tecnologia. Mio padre, Meneleaos, un ingegnere civile che ha appena pubblicato il suo libro a 80 anni, era colui che mi ha insegnato il pensiero logico e analitico e mi ha trasmesso un amore per la scienza e l ingegneria. Grazie a tutti per avermi aiutato durante questo viaggio. Bozza della Early Release (Contributi da GitHub) Moltri contributor hanno offerto commenti, correzioni e aggiunte alla bozza di pre-release su GitHub. Grazie a tutti i vostri contributi che avete dato a questo libro. Di seguito una lista di noti contributor sul progetto bitcoinbook su GitHub, inclusi i loro GitHub ID tra parentesi: Minh T. Nguyen, GitHub editor delle contributions (enderminh) Ed Eykholt (edeykholt) Michalis Kargakis (kargakis) Erik Wahlström (erikwam) Richard Kiss (richardkiss) Eric Winchell (winchell) Sergej Kotliar (ziggamon) Nagaraj Hubli (nagarajhubli) ethers Alex Waters (alexwaters) Mihail Russu (MihailRussu) Ish Ot Jr. (ishotjr) James Addison (jayaddison) Nekomata (nekomata-3) Simon de la Rouviere (simondlr) 4

7 Chapman Shoop (belovachap) Holger Schinzel (schinzelh) effectstocause (vericoin) Stephan Oeste (Emzy) Joe Bauers (joebauers) Jason Bisterfeldt (jbisterfeldt) Ed Leafe (EdLeafe) Open Edition This is the open edition of "Mastering Bitcoin", published for translation under a Creative Commons Attribution Share-Alike License (CC-BY-SA). This license allows you to read, share, copy, print, sell, or re-use this book or parts of this book, if you: Apply the same license (Share-Alike) Include attribution Attribution Mastering Bitcoin by Andreas M. Antonopoulos LLC Copyright 2016, Andreas M. Antonopoulos LLC Translation If you are reading this book in a language other than English, it has been translated by volunteers. The following people contributed to this translation: Add names of translators when translating Name 2 Name 3 5

8 Glossario Questo glossario comprende molti dei termini usati con riferimento al bitcoin. Si tratta di parole usate di frequente nel testo quindi si consiglia di memorizzarle per una rapida consultazione. indirizzo Un indirizzo bitcoin si presenta come segue: 1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV ovvero una stringa di lettere e numeri che comincia con il numero "1". Così come usiamo un indirizzo per farci spedire una , alla stessa maniera utilizziamo il nostro indirizzo bitcoin per farci spedire dei bitcoin. bip Proposte di miglioramento per il Bitcoin. Un insieme di proposte che i membri della comunità bitcoin hanno presentato per migliorare i bitcoin. Ad esempio, BIP0021 è una proposta per migliorare lo schema dell uniform resource identifier (URI). bitcoin Il nome dell unità di valuta (la moneta), il network e il software. blocco Un gruppo di transazioni, marchiate da un timestamp e dall impronta univoca del blocco precedente. Per poter fornire una soluzione proof of work, è necessario calcolare l header del blocco, e successivamente validare le transazioni. I blocchi validi sono inseriti all interno della blockchain principale mediante il consenso della rete. blockchain Una lista di blocchi validati, ognuno che collega il precedente fino al blocco di origine (genesis block). conferme Quando una transazione viene inclusa in un blocco, ha una conferma. Non appena un altro blocco verrà validato nella stessa blockchain, la transazione avrà due conferme, e così via. Sei o più conferme sono considerate una prova sufficiente che la transazione non possa essere annullata. difficoltà Un impostazione valida per tutta la rete, che regolamenta quanta potenza computazionale è necessaria per produrre una soluzione proof of work. difficoltà calcolata La difficoltà a cui tutta la potenza computazionale della rete troverà nuovi blocchi approssimativamente ogni 10 minuti. difficulty retargeting Un ricalcolo della difficoltà per tutta la rete, che si verifica ogni blocchi, e tiene in 1

9 considerazione la potenza di calcolo dei blocchi precedenti. commissioni Il mittente di una transazione, spesso vi accorpa il pagamento di una tariffa per la rete, che processerà la transazione richiesta. La maggior parte delle transazioni richiede il pagamento di una tariffa minima di 0.5 mbtc hash L impronta digitale di un certo input binario. genesis block Il primo blocco della blockchain, utilizzato per inizializzare la criptovaluta. minatore Un nodo della rete che trova soluzioni valide alla proof of work per i nuovi blocchi, mediante numerosi calcoli. rete Una rete peer-to-peer che propaga le transazioni e i blocchi a tutti i nodi bitcoin della stessa. Proof-Of-Work Una porzione di dati che richiede un significativo sforzo computazionale, per essere trovata. In bitcoin, i minatori devono trovare una soluzione numerica all algoritmo SHA256 che soddisfa un obiettivo stabilito dall intera rete, la difficoltà calcolata. ricompensa Un ammontare, incluso in ogni nuovo blocco, quale ricompensa dalla rete per il minatore che troverà la soluzione Proof-Of-Work. Al momento è pari a 25BTC per blocco. chiave segreta (o chiave privata) Un numero segreto che sblocca i bitcoin inviati all indirizzo corrispondente. Una chiave segreta è rappresentata da una stringa alfanumerica simile a 5J76sF8L5jTtzE96r66Sf8cka9y44wdpJjMwCxR3tzLh3ibVPxh. transazione In parole povere, un trasferimento di bitcoin da un indirizzo ad un altro. Più precisamente, una transazione è una struttura di dati che esprime un trasferimento di valore. Le transazioni sono trasmesse attraverso la rete bitcoin, raggruppate dai minatori ed incluse all interno di blocchi, registrati permanentemente nella blockchain. wallet Un software che conserva tutti i tuoi indirizzi bitcoin e le chiavi private. Usalo per inviare, ricevere e conservare i tuoi bitcoin. 2

10 Introduzione Cos è Bitcoin? Bitcoin è una collezione di concetti e tecnologie che formano le basi per un ecosistema di monete digitali. Unità di moneta chiamati bitcoin vengono utilizzati per immagazzinare e trasferire valore tra i partecipanti del network Bitcoin. Gli utenti Bitcoin comunicano tra loro utilizzando il protocollo Bitcoin principalmente attraverso internet, anche se sono possibili altri network di trasporto. L intero protocollo Bitcoin, disponibile come software open source, può essere utilizzato su un ampia gamma di dispositivi digitali, inclusi laptops e cellulari, rendendo questa tecnologia facilmente accessibile. Gli utenti possono trasferire bitcoin sulla rete per fare qualunque cosa sia possibile fare con le valute tradizionali, incluso comprare e vendere beni, mandare soldi a persone o organizzazioni, oppure fare credito. I bitcoin possono essere comprati, venduti, e scambiati con altre valute su specifici mercati di cambio. Bitcoin rappresenta in un certo senso la forma di denaro perfetta per Internet perché è veloce, sicuro e senza frontiere. A differenza delle monete tradizionali, i bitcoin sono completamente virtuali. Non c è moneta fisica e neanche monete digitali in se per se. La moneta è sottintesa nelle transazioni che trasferiscono valuta dal mittente al ricevente. Gli utenti di bitcoin utilizzano le proprie chiavi che permettono loro di avere la prova di essere i proprietari delle transazioni nel network bitcoin, sbloccando la valuta da spendere e trasferendola al nuovo ricevente. Queste chiavi sono generalmente contenute in portafogli (wallet) digitali nei computer di ciascun utente. Il possesso delle chiavi che sbloccano una transazione è il solo prerequisito per spendere i bitcoin, mettendo il controllo dei propri bitcoin interamente nelle mani di ogni utente. Bitcoin è un sistema distribuito e peer-to-peer. In quanto tale non ha alcun server "centrale", o centro di controllo. I bitcoin sono creati tramite un processo chiamato "mining", che comporta una competizione per cercare le soluzioni di un complesso problema matematico mentre vengono processate le transazioni. Ogni partecipante al network bitcoin (cioè chiunque stia usando un dispositivo che esegue un istanza completa del protocollo) può operare come "minatore", usando la potenza di calcolo del proprio computer per verificare e registrare le transazioni. In media ogni 10 minuti, qualcuno è in grado di validare le transazioni dei 10 minuti precedenti ed è ricompensato con bitcoin nuovi di zecca. Essenzialmente, il mining di bitcoin decentralizza le funzioni di emissione di valuta e di compensazione attualmente tipiche di una banca centrale, e rimpiazza la necessità di qualunque banca centrale con questa competizione globale. Il protocollo bitcoin include algoritmi incorporati in esso che regolano la funzione di mining su tutto il network. La difficoltà del problema che i miner devono risolvere utilizzando potenza computazionale per il salvataggio di un blocco di transazioni è aggiustata automaticamente di modo che, di media, si arrivi a una soluzione del problema ogni 10 minuti qualunque sia il numero dei miner (e CPU) che stanno lavorando alla risoluzione problema in ogni momento. Il protocollo inoltre dimezza il tasso per il quale nuovi bitcoin sono creati, ogni quattro anni, e limita il numero totale di bitcoin che saranno creati a un numero fisso massimo di 21 milioni di bitcoin. Il risultato è che il numero di 1

11 bitcoin in circolazione è molto vicino a essere una curva prevedibile che raggiungerà 21 milioni entro l anno A causa del tasso di emissione dei bitcoin in diminuzioni, a lungo termine, la valuta bitcoin è deflazionaria. Per questo, bitcoin non può essere inflazionata stampando nuova moneta al di sopra e oltre il limite dato dal tasso di emissione previsto. Dietro le quinte bitcoin è anche il nome del protocollo, del network e dell innovazione informatica distribuita. La valuta bitcoin è davvero solo la prima applicazione di questa invenzione. Come programmatore, vedo bitcoin come qualcosa di simile all Internet del denaro, un network per trasportare valore e assicurare la proprietà di asset digitali tramite computazione distribuita. Bitcoin è molto di più di ciò che appare a prima vista. In questo capitolo inizieremo a spiegare alcuni dei principali concetti e termini, come ottenere il software necessario, e l uso di bitcoin per effettuare semplici transazioni. Nei capitoli seguenti inizieremo a scoprire i vari livelli della tecnologia che rendono bitcoin possibile e esamineremo i funzionamenti interni della rete bitcoin e del protocollo. Valute Digitali Pre-Bitcoin L emergenza della moneta digitale fruibile è strettamente collegata agli sviluppi in cittografia. Questo non deve sorprendere quando si considera le sfide fondamentali che si hanno quando si usano i bit per rappresentare valori che possono essere scambiati per beni e servizi. Due domande base per chiunque accetti denaro in forma digitale sono: 1. Posso fidarmi che i soldi siano autentici e non contraffati? 2. Posso essere sicuro che nessun altro possa reclamare che i fondi appartengono a loro e non a me? (Aka il problema del double-spend.) Issuers of paper money are constantly battling the counterfeiting problem by using increasingly sophisticated papers and printing technology. Physical money addresses the double-spend issue easily because the same paper note cannot be in two places at once. Of course, conventional money is also often stored and transmitted digitally. In these cases, the counterfeiting and double-spend issues are handled by clearing all electronic transactions through central authorities that have a global view of the currency in circulation. For digital money, which cannot take advantage of esoteric inks or holographic strips, cryptography provides the basis for trusting the legitimacy of a user s claim to value. Specifically, cryptographic digital signatures enable a user to sign a digital asset or transaction proving the ownership of that asset. With the appropriate architecture, digital signatures also can be used to address the double-spend issue. Quando la crittografia è iniziata a diventare sempre più disponibile e compresa alla fine degli anni '80, molti ricercatori hanno iniziato a provare a usare la crittografia per realizzare monete digitali. Questi primi progetti di monete digitali emettevano valuta digitale, generalmente sostenuta da una moneta nazionale o da metalli preziosi come l oro. Nonostante queste prime valute digitali funzionassero, erano centralizzate e quindi, di conseguenza, facili prede di attacchi da parte di governi e hacker. Le prime valute digitali 2

12 usavano una camera di compensazione centrale per gestire le transazioni a intervalli regolari, proprio come un sistema bancario tradizionale. Sfortunatamente, in molti casi queste neonate valute digitali furono prese di mira da governi preoccupati e con il tempo sommerse di contenziosi fino alla loro scomparsa. Alcune fallirono i crolli spettacolari quando la compagnia di emissione andò improvvisamente in liquidazione. Per essere resistenti agli attacchi di enti antagonisti, che si trattasse di istituzioni legali o di criminali, era necessaria una valuta decentralizzata priva di un singolo punto di rottura. Bitcoin è questo sistema, disegnato per essere completamente decentralizzato, e libero da qualunque autorità centrale o centro di controllo che possa essere attaccato o compromesso. Bitcoin rappresenta il culmine di decenni di ricerca nei campi della crittografia e dei sistemi distribuiti e comprende quattro diverse innovazioni-chiave, portate insieme in un unica e potente combinazione. Bitcoin consiste in: Un network peer-to-peer decentralizzato (il protocollo bitcoin) Un libro-mastro di transazioni pubblico (la blockchain) Un emissione della moneta decentralizzata, matematica e deterministica (mining distribuito) Un sistema decentralizzato di verifica delle transazioni (lo script delle transazioni) Storia di Bitcoin Bitcoin was invented in 2008 with the publication of a paper titled "Bitcoin: A Peer-to-Peer Electronic Cash System," written under the alias of Satoshi Nakamoto. Nakamoto combined several prior inventions such as b-money and HashCash to create a completely decentralized electronic cash system that does not rely on a central authority for currency issuance or settlement and validation of transactions. The key innovation was to use a distributed computation system (called a "proof-of-work" algorithm) to conduct a global "election" every 10 minutes, allowing the decentralized network to arrive at consensus about the state of transactions. This elegantly solves the issue of double-spend where a single currency unit can be spent twice. Previously, the double-spend problem was a weakness of digital currency and was addressed by clearing all transactions through a central clearinghouse. The bitcoin network started in 2009, based on a reference implementation published by Nakamoto and since revised by many other programmers. The distributed computation that provides security and resilience for bitcoin has increased exponentially, and now exceeds that combined processing capacity of the world s top super-computers. Bitcoin s total market value is estimated at between 5 billion and 10 billion US dollars, depending on the bitcoin-to-dollar exchange rate. The largest transaction processed so far by the network was 150 million US dollars, transmitted instantly and processed without any fees. Satoshi Nakamoto si ritirò dalla scena pubblica nell Aprile del 2011, lasciando la responsabilità dello sviluppo del codice e del network a una fiorente comunità di volontari. L identità della persona o del gruppo dietro bitcoin è ancora un mistero. Ad ogni modo, né Satoshi Nakamoto né chiunque altro può esercitare alcun controllo sul sistema bitcoin, che opera sulla base di principi matematici 3

13 completamente trasparenti. L invenzione è di per sé rivoluzionaria e ha già generato nuovi traguardi scientifici nei campi dell informatica distribuita, dell economia e dell econometria. Una Soluzione a un Problema Computazionale Distribuito Satoshi Nakamoto s invention is also a practical solution to a previously unsolved problem in distributed computing, known as the "Byzantine Generals' Problem." Briefly, the problem consists of trying to agree on a course of action by exchanging information over an unreliable and potentially compromised network. Satoshi Nakamoto s solution, which uses the concept of proof-of-work to achieve consensus without a central trusted authority, represents a breakthrough in distributed computing science and has wide applicability beyond currency. It can be used to achieve consensus on decentralized networks to prove the fairness of elections, lotteries, asset registries, digital notarization, and more. I vari Utilizzi di Bitcoin, gli Utenti e le loro Storie Bitcoin è una tecnologia, ma serve a gestire il denaro che è fondamentalmente un linguaggio per scambiare valore tra le persone. Andiamo ad esaminare le tipologie di persona che utilizzano attualmente bitcoin e, attraverso le loro storie, gli usi più comuni della valuta e del protocollo. Utilizzeremo nuovamente queste storie nel corso del libro per illustrare le modalità concrete di utilizzo del denaro digitale ed il modo con cui sono rese possibili dalle diverse tecnologie che costituiscono bitcoin. Negozio Nord Americano di prodotti comuni Alice vive nella Bay Area, nel nord della California. Ha sentito parlare di bitcoin dai suoi amici appassionati di tecnologia e vuole cominciare ad utilizzarlo. Seguiremo la sua storia mentre impara cos è bitcoin, acquista un po' di valuta e ne spende una parte per comprare un caffè al Bob s Cafe di Palo Alto. Questa storia ci introdurrà al software di base, agli exchange e alle transazioni più semplici dal punto di vista di un consumatore finale. Negozio di cose di valore Nord Americano Carol è proprietaria di una galleria d arte in San Francisco. Vende quadri costosi in cambio di bitcoin. Questa storia introdurrà il rischio di un "attacco 51%" per venditori di oggetti di valore. Servizi di liberi professionisti esteri Bob, il proprietario del caffè a Palo Alto, sta creando un nuovo sito internet. Ha assunto un webdeveloper indiano, Gopesh, che vive a Bangalore, in India. Gopesh ha accettato di essere pagato in bitcoin. Questa storia illustrerà l uso di bitcoin per l outsourcing, i lavori a contratto e i trasferimenti internazionali di denaro. Donazioni Eugenia è la direttrice di un ente di beneficenza focalizzato sui bambini nelle Filippine. Recentemente ha scoperto bitcoin e vuole utilizzarlo per raggiungere un settore totalmente nuovo 4

14 di donatori stranieri e domestici per finanziare il suo ente benefico. Sta anche investigando la possibilità di usare bitcoin per distribuire velocemente le risorse alle aree di necessità. Questa storia mostrerà l uso di bitcoin per la raccolta di fondi globale attraverso frontiere e valute differenti, e l utilizzo di un registro pubblico ai fini di trasparenza in organizzazioni filantropiche. Import/export Mohammed è un importatore di elettronica a Dubai. Sta cercando di usare bitcoin per comprare ed importare negli Emirati Arabi Uniti componenti elettroniche provenienti dagli USA e dalla Cina, sperando di accelerare il processo di dei pagamenti nella fase di importazione. Questa storia mostrerà come bitcoin può essere utilizzato per importanti pagamenti internazionali da azienda ad azienda relativi a beni fisici. Bitcoin Mining Jing è uno studente di ingegneria informatica a Shanghai. Ha costruito una "mining rig" per fare mining di bitcoin, utilizza le sue abilità da informatico per avere un reddito supplementare. Questa storia esaminerà la base "industriale" di bitcoin: l attrezzatura specializzata usata per proteggere il network bitcoin da attacchi informatici e per emettere nuova moneta. Ognuna di queste storie è basata su personi reali e su settori commerciali reali che stanno correntemente usando bitcoin per creare nuovi mercati, nuovi settori e soluzioni innovative a problemi economici globali. Per Iniziare Per entrare a far parte del network bitcoin e per iniziare a usare la valuta, tutto quello che deve fare un utente è scaricare un applicazione o utilizzare un applicazione web. Visto che bitcoin è uno standard, ci sono varie implementazioni del software client di bitcoin. C è anche un implementazione di riferimento, conosciuta anche con il nome di Satoshi client, che è gestita come un progetto open source da un team di sviluppatori ed è derivata dall implementazione originale scritta da Satoshi Nakamoto. Le tre forme principali di client bitcoin sono: Full client Un full client, o "full node," è un client che salva la storia coompleta delle transazioni bitcoin (ogni transazione, da ogni utente, da sempre), che gestisce i wallet dell utente, e che può iniziare le transazioni direttamente sul network bitcoin. Questo è simile a un server , visto che gestisce tutti gli aspetti del protocollo senza fare affidamento su altri server o su servizi di terza parte. Client leggeri Un client leggero (light client) registra il wallet utente ma fa affidamento a server di proprietà di terze parti per accedere alla rete e alle transazioni bitcoin. Il light client non salva la copia di tutte le transazioni e quindi deve findarsi dei server di terze parti per la validazione delle transazioni. Questo è molto simile a un client mail indipendente che si connette a un server di posta per accedere a una casella di posta, col fatto che si appoggia su un server di terze perti per interagire 5

15 con il network. Client web I client web sono quelli a cui si accede tramite un web browser e che salvano il wallet dell utente su di un server controllato da una terza parte. Questo è molto simile a una webmail per il fatto che si fa affidamento interamente su un server di terze parti. Bitcoin su Cellulari I client mobile per smartphone, come quelli basati su sul sistema Android, possono operare sia come full client, light client o web client. Molti client mobile sono sincronizzati con un client web o desktop, fornendo un wallet multipiattaforma su multipli dispositivi ma con una fonte comune di fondi. La scelta del client bitcoin dipende da quanto controllo l utente vuole avere sui propri fondi. Un client completo offrirà all utente il livello più alto di controllo e di indipendenza, ma lascerà il peso di backup e sicurezza interamente sulle sue spalle. All altro estremo dello spettro di scelte, un client web è il più facile da impostare ed utilizzare, ma il lato negativo di una simile soluzione è l introduzione di un rischio di controparte, perché la sicurezza e il controllo sui fondi sono condivisi tra utente e gestore del servizio. Se un servizio di wallet su web è compromesso, come è successo in molti casi, gli utenti possono perdere tutti i loro fondi. Viceversa, se un utente utilizza un client indipendente senza adeguate strategie di backup, potrebbe perdere i suoi fondi a causa di una disavventura informatica. Per lo scopo di questo libro, dimostreremo l utilizzo di un vario tipo di client bitcoin scaricabili, dall implementazione di riferimento (reference client, il Satoshi client) a wallet web. Molti di questi esempi richiederanno l utilizzo del reference client, il quale, oltre a essere un full client, espone anche un API per il wallet, per il network e per i servizi di transazione. Se prevedi di esplorare le interfacce di programmazione del sistema bitcoin, ti servirà il reference client. Quick Start Alice, who we introduced in I vari Utilizzi di Bitcoin, gli Utenti e le loro Storie, is not a technical user and only recently heard about bitcoin from a friend. She starts her journey by visiting the official website bitcoin.org, where she finds a broad selection of bitcoin clients. Following the advice on the bitcoin.org site, she chooses the lightweight bitcoin client Multibit. Alice segue un link dal sito di bitcoin.org per scaricare e installare Multibit sul suo computer fisso. Multibit è disponibile per computer fissi con Windows, Mac OS, e Linux. 6

16 A bitcoin wallet must be protected by a password or passphrase. There are many bad actors attempting to break weak passwords, so take care to select one that cannot be easily broken. Use a combination of upper and lowercase characters, numbers, and symbols. Avoid personal information such as birth dates or names of sports teams. Avoid any words commonly found in dictionaries, in any language. If you can, use a password generator to create a completely random password that is at least 12 characters in length. Remember: bitcoin is money and can be instantly moved anywhere in the world. If it is not well protected, it can be easily stolen. Una volta che Alice ha scaricato e installato l applicazione Multibit, la lancia ed è accolta da una schermata di benvenuto, mostrata nel La schermata iniziale del client bitcoin Multibit. Figure 1. La schermata iniziale del client bitcoin Multibit Multibit automatically creates a wallet and a new bitcoin address for Alice, which Alice can see by clicking the Request tab shown in Il nuovo indirizzo bitcoin di Alice, nella tab Request del client Multibit. 7

17 Figure 2. Il nuovo indirizzo bitcoin di Alice, nella tab Request del client Multibit The most important part of this screen is Alice s bitcoin address. Like an address, Alice can share this address and anyone can use it to send money directly to her new wallet. On the screen it appears as a long string of letters and numbers: 1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK. Next to the wallet s bitcoin address is a QR code, a form of barcode that contains the same information in a format that can be scanned by a smartphone camera. The QR code is the black-and-white square on the right side of the window. Alice can copy the bitcoin address or the QR code onto her clipboard by clicking the copy button adjacent to each of them. Clicking the QR code itself will magnify it, so that it can be easily scanned by a smartphone camera. Alice può anche stampare il codice QR come mezzo per dare ad altri il proprio indirizzo in modo semplice, senza obbligarli a digitare una lunga stringa di lettere e numeri. TIP Bitcoin addresses start with the digit 1 or 3. Like addresses, they can be shared with other bitcoin users who can use them to send bitcoin directly to your wallet. Unlike addresses, you can create new addresses as often as you like, all of which will direct funds to your wallet. A wallet is simply a collection of addresses and the keys that unlock the funds within. You can increase your privacy by using a different address for every transaction. There is practically no limit to the number of addresses a user can create. Alice è ora pronta a usare il suo nuovo wallet bitcoin. Ottenere I Tuoi Primi Bitcoin It is not possible to buy bitcoins at a bank or foreign exchange kiosks at this time. As of 2014, it is still quite difficult to acquire bitcoins in most countries. There are a number of specialized currency exchanges where you can buy and sell bitcoin in exchange for a local currency. These operate as webbased currency markets and include: 8

18 Bitstamp Un mercato di valute europeo che supporta molte valute che includono euro (EUR) e dollari americani (USD) attraverso bonifico bancario. Coinbase Una piattaforma wallet e piattaforma basata in USA dove venditori e consumatori possono effettuare transazioni in bitcoin. Coinbase rende facile comprare e vendere bitcoin, consentendo agli utenti di connettersi ai conti correnti USA tramite il sistema ACH. Cryptocurrency exchanges such as these operate at the intersection of national currencies and cryptocurrencies. As such, they are subject to national and international regulations, and are often specific to a single country or economic area and specialize in the national currencies of that area. Your choice of currency exchange will be specific to the national currency you use and limited to the exchanges that operate within the legal jurisdiction of your country. Similar to opening a bank account, it takes several days or weeks to set up the necessary accounts with these services because they require various forms of identification to comply with KYC (know your customer) and AML (antimoney laundering) banking regulations. Once you have an account on a bitcoin exchange, you can then buy or sell bitcoins quickly just as you could with foreign currency with a brokerage account. Puoi trovare una lista più completa su bitcoin charts, un sito che offre quotazioni di prezzo e altri dati di mercato di molte decine di currency exchanges. Ci sono quattro altri metodi per ottenere bitcoin come nuovo utente: Trova un amico che ha bitcoin e ne compra alcuni da lui direttamente. Molti utenti bitcoin iniziano in questo modo. Utilizzare un servizio privato come localbitcoins.com per trovare un venditore nella vostra zona per comprare bitcoin per contanti con una transazione di persona Vendi un prodotto o offri un servizio in cambio di bitcoin. Se sei un programmatore, offri le tue conoscenze in programmazione. Utilizza un ATM bitcoin nella tua città. Trova un ATM bitcoin vicino a te utilizzando una mappa online di CoinDesk. Alice è venuta in contatto con bitcoin tramite un amico e di conseguenza ha un canale facilitato per ottenere i suoi primi bitcoin intanto che aspetta la verifica e l attivazione del proprio account su un mercato dei cambi californiano. Inviare e Ricevere Bitcoin Alice has created her bitcoin wallet and she is now ready to receive funds. Her wallet application randomly generated a private key (described in more detail in [private_keys]) together with its corresponding bitcoin address. At this point, her bitcoin address is not known to the bitcoin network or "registered" with any part of the bitcoin system. Her bitcoin address is simply a number that corresponds to a key that she can use to control access to the funds. There is no account or association between that address and an account. Until the moment this address is referenced as the recipient of 9

19 value in a transaction posted on the bitcoin ledger (the blockchain), it is simply part of the vast number of possible addresses that are "valid" in bitcoin. Once it has been associated with a transaction, it becomes part of the known addresses in the network and Alice can check its balance on the public ledger. Alice incontra il suo amico Joe, che le aveva parlato di bitcoin, in un ristorante locale, così da poter scambiare qualche dollaro americano e mettere qualche bitcoin nel suo conto. Lei ha portato una stampa del suo indirizzo e del relativo codice QR, così come visualizzato nel suo wallet. L indirizzo bitcoin non rappresenta un dato sensibile, dal punto di vista della sicurezza. Può essere lasciato in vista ovunque senza alcun rischio per la sicurezza del suo conto. Alice vuole convertire 10 dollari in bitcoin, non correndo il rischio di perdere troppi soldi in questa nuova tecnologia. Alice da una banconota di 10$ a Joe e un foglio stampato con scritto scritto il proprio indirizzo di modo che Joe possa inviarle la somma equivalente di bitcoin. Successivamente, Joe deve scoprire il tasso di cambio (exchange rate) di modo che possa dare la somma corretta di bitcoin ad Alice. Ci sono centinaia di applicazioni e siti che possono provvedere il tasso di cambio corrente. Qua possiamo trovare alcuni dei più famosi: Bitcoin Charts Un servizio di listing dei dati di mercato che mostra il valore di mercato di bitcoin nei vari exchange in tutto il mondo, denominato nelle varie valute locali Bitcoin Average Un sito che mostra una semplice pagina con la media-pesata rispetto al volume per ogni valuta ZeroBlock Un applicazione gratuita per Android e ios che può mostrare il prezzo del bitcoin da diverse exchange (vedi ZeroBlock, un applicazione per vedere il cambio del bitcoin per Android e ios) Bitcoin Wisdom Un altro servizio di quotazione Figure 3. ZeroBlock, un applicazione per vedere il cambio del bitcoin per Android e ios Using one of the applications or websites just listed, Joe determines the price of bitcoin to be approximately 100 US dollars per bitcoin. At that rate he should give Alice 0.10 bitcoin, also known as 100 millibits, in return for the 10 US dollars she gave him. 10

20 Once Joe has established a fair exchange price, he opens his mobile wallet application and selects to "send" bitcoin. For example, if using the Blockchain mobile wallet on an Android phone, he would see a screen requesting two inputs, as shown in La schermata send del mobile wallet Blockchain. L indirizzo bitcoin di destinazione per la transazione La somma di bitcoin da inviare In the input field for the bitcoin address, there is a small icon that looks like a QR code. This allows Joe to scan the barcode with his smartphone camera so that he doesn t have to type in Alice s bitcoin address (1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK), which is quite long and difficult to type. Joe taps the QR code icon and activates the smartphone camera, scanning the QR code from Alice s printed wallet that she brought with her. The mobile wallet application fills in the bitcoin address and Joe can check that it scanned correctly by comparing a few digits from the address with the address printed by Alice. Figure 4. La schermata send del mobile wallet Blockchain Joe then enters the bitcoin value for the transaction, 0.10 bitcoin. He carefully checks to make sure he has entered the correct amount, because he is about to transmit money and any mistake could be costly. Finally, he presses Send to transmit the transaction. Joe s mobile bitcoin wallet constructs a transaction that assigns 0.10 bitcoin to the address provided by Alice, sourcing the funds from Joe s wallet and signing the transaction with Joe s private keys. This tells the bitcoin network that Joe has authorized a transfer of value from one of his addresses to Alice s new address. As the transaction is transmitted via the peer-to-peer protocol, it quickly propagates across the bitcoin network. In less than a second, most of the well-connected nodes in the network receive the transaction and see Alice s address for the first time. If Alice has a smartphone or laptop with her, she will also be able to see the transaction. The bitcoin ledger a constantly growing file that records every bitcoin transaction that has ever occurred is public, meaning that all she has to do is look up her own address and see if any funds have been sent to it. She can do this quite easily at the blockchain.info website by entering her address in the search box. The website will show her a page listing all the transactions to and from that address. If Alice is 11

21 watching that page, it will update to show a new transaction transferring 0.10 bitcoin to her balance soon after Joe hits Send. Confierme Per prima cosa, l indirizzo di alice mostrerà la transazione di Joe come "Unconfirmed" (non ancora confermata). Questo significa che la transazione è stata propagata sul network ma non è stata ancora inclusa nel registro di transazioni bitcoin, conosciuto come blockchain. Per essere inclusa, la transazione dovrà essere "pescata" da un miner e inclusa in un blocco di transazioni. Una volta che un nuovo blocco è stato formato, in circa 10 minuti, la transazione contenuta nel blocco sarà accettata e considerata "confermata" (Confirmed) dal network e potrà essere spesa. La transazione è vista da tutti istantaneamente, ma è "considerata valida" da tutti solo quando è stata inclusa in un nuovo blocco che abbia ricevuto la conferma del mining. Alice è adesso fiera di essere la proprietaria di 0.10 bitcoin che può spendere. Nel prossimo capitolo osserveremo il suo primo acquisto con bitcoin, e esamineremo la transazione sottostante e le tecnologie di propagazione più in dettaglio. 12

22 Come Funziona Bitcoin Transazioni, Blocchi, Mining, e la Blockchain Il sistema di bitcoin, al contrario dei tradizionali sistemi bancari e dei sistemi di pagamento, è basato sulla decentralizzazione della fiducia. Invece di un autorità centrale fiduciaria, in bitcoin, la fiducia si ottiene come proprietà emergente dall interazione di diversi partecipanti nel sistema bitcoin. In questo capitolo, esamineremo bitcoin da "lontano" seguendo una singola transazione attraverso il sistema bitcoin e osservando come ottiene la "ficucia" e viene accettada dal meccanismo di bitcoin del consenso distrubito e finalmente registrata sulla blockchain, il libro mastro di tutte le transazioni. Ogni esempio è basato sulle transazioni effettive fatte sul network bitcoin, simulando le interazioni tra gli utenti (Joe, Alice e Bob) inviando i fondi da un portafoglio all altro. Per tracciare una transazione attraverso il network bitcoin e la blockchain, useremo un sito_blockchain explorer_ per visualizzare ogni passaggio. Un sito blockchain explorer è un applicazione web che opera come un motore di ricerca bitcoin, in esso permette di cercare per indirizzo, transazione e blocco per vedere i relativi rapporti e flussi di essi. Blockchain explorers conosciuti includono: Blockchain info Bitcoin Block Explorer insight blockr Block Reader Ogniuno di questi ha una funzione di ricerca che accetta un indirizzo, un hash di una transazione o il numero di un blocco e trovare i dati equivalenti sul network bitcoin e sulla blockchain. Con ogni esempio, forniremo un indirizzo web (URL) che porterà direttamente all elemento corrispondente, così che potrete studiarli in dettaglio. Panoramica su Bitcoin Nel diagramma panoramico mostrato su Panoramica su Bitcoin. noteremo che il sistema bitcoin consiste di utenti con portafogli (wallet) contenenti chiavi (key), le transazioni sono propagate attraverso il network, i miner che producono (tramite una gara di computazione) la blockchain (catena di blocchi) del consenso, che è il libro mastro autoritativo di tutte le transazioni. In questo capitolo, seguiremo una singola transazione che viaggia attraverso il network e esamineremo l interazione tra ogni parte del sistema bitcoin, ad alto livello. I capitoli successivi investigheranno nelle tecnologie che stanno dietro i wallet, il mining e sui sistemi commerciali. 1

23 Figure 1. Panoramica su Bitcoin Pagare un Caffè Alice, introdotta nel capitolo precedente, è un nuovo utente che ha appena ottenuto il suo primo bitcoin. In [getting_first_bitcoin], Alice si è incontrata con il suo amico Joe per scambiare un po di denaro contante per bitcoin. La transazione creata da Joe ha riempito il wallet di Alice con 0.10 BTC. Ora Alice potrà fare la sua prima transazione in un negozio, comprando un caffè al bar di Bob a Palo Alto, Califorinia. Il bar di Bob ha recentemente iniziato ad accettare pagamenti in bitcoin, aggiungendo una opzione bitcoin al suo sistema POS (point-of-sale). I prezzi al Bar di Bob sono elencati nella valuta locale (dollari), ma alla cassa, i clienti hanno la possibilità di pagare sia in dollari che in bitcoin. Il POS, convertirà il prezzo totale da dollari americani a bitcoin al miglior prezzo di mercato e mostrerà i prezzi in entrambe le valute, inoltre mostrerà un QR code contenente una richiesta di pagamento per la transazione (vedi Il QR code della richiesta di pagamento (Indizio: Prova a scansionarlo!)): Totale: $1.50 USD BTC 2

24 Figure 2. Il QR code della richiesta di pagamento (Indizio: Prova a scansionarlo!) Il QR code con la richiesta di pagamento contiene il seguente URL, definito in BIP0021: bitcoin:1gdk9uzphbzqzx2a9jfp3di4webwqgmoqa? amount=0.015& label=bob%27s%20cafe& message=purchase%20at%20bob%27s%20cafe Parti dell'url Un indirizzo bitcoin: "1GdK9UzpHBzqzX2A9JFP3Di4weBwqgmoQA" L'importo del pagamento: "0.015" Un'etichetta per l'indirizzo del destinatario: "Bob's Cafe" Una descrizione del pagamento: "Acquisto al Bar di Bob" TIP Invece di un QR code che contiene semplicemente un indirizzo bitcoin di destinazione, una richiesta di pagamento (payment request) è un URL sotto forma di QR code che contiene un indirizzo bitcoin di destinazione, il valore del pagamento, e una descrizione generica come "Bar di Bob". Questo consente ad un applicazione wallet bitcoin di precompilare le informazioni usate per inviare il pagamento e al tempo stesso mostrare all utente una descrizione leggibile dell operazione. Puoi scansionare il QR code qui presente con un applicazione wallet bitcoin per vedere cosa vedrebbe Alice. Bob dice, "Costa un dollaro e cinquanta, o cinque millibit." Alice usa il suo smartphone per scansionare il codice a barre mostrato sullo schermo. Il suo smartphone mostra un pagamento di BTC al Bar di Bob e dopo lei seleziona Invia (Send) per autorizzare la transazione. Nel giro di pochi secondi (circa lo stesso tempo di un autorizzazione di una carta di credito), Bob sarà in grado di visualizzare la transazione sulla cassa del bar, e la transazione sarà in questo modo completa. Nelle sezioni seguenti esamineremo dettagliatamente la precedente transazione, vedremo come il wallet di Alice l ha costruita.todo 3

25 Il network bitcoin può effettuare transazioni in valori frazionari, es. da millibitcoin (un millesimo di bitcoin) fino a 1/ mo di bitcoin, che è anche conosciuto come un satoshi. Per tutto il libro useremo il termine "bitcoin" per riferirci a qualsiasi quantità di valuta bitcoin, dalla sua unità più piccola (1 satoshi) al numero totale ( ) di tutti i bitcoin che saranno mai minati. Transazioni Bitcoin In parole povere, una transazione comunica al network che il proprietario di un certo numero di bitcoin ha autorizzato il trasferimento di una parte di essi ad un altro proprietario. Il nuovo proprietario può ora spendere questi bitcoin creando un altra transazione che autorizza il trasferimento a un nuovo proprietario, e così via, formando una catena di passaggi di proprietà. Le transazioni sono come righe in un registro di contabilità in partita doppia. In parole povere, ogni transazione contiene uno o più "input", che sono debiti verso un account bitcoin. Dall altro lato della transazione, ci sono uno o più "output", che sono crediti aggiunti ad un account bitcoin. Gli input e gli output (debiti e crediti) se sommati, non totalizzano necessariamente lo stesso risultato. Al contrario, gli output totalizzano un risultato poco inferiore a quello degli input e la differenza rappresenta una "commissione di transazione" (transaction fee) sottintesa, che è un piccolo pagamento che il miner che include la transazione nel registro ottiene. Una transazione bitcoin è mostrata come una riga in un registro di contabilità in Transazioni come libro di contabilità in partita doppia. La transazione contiene anche una prova di propietà (proof of ownership) per ogni quantità di bitcoins (inputs) che viene trasferita, attraverso una firma digitale del possessore, che può essere validata indipendentemente da chiunque. In termini di bitcoin, "spendere" vuol dire firmare una transazione che trasferisce valore da una precedente transazione ad un nuovo proprietario identificato da un indirizzo bitcoin. TIP Le transazioni muovono valuta dagli input di transazione agli output di transazione. Un input è laddove proviene il valore dei bitcoin, generalmente da un output di una transazione precedente. Un output di transazione assegna un nuovo utente al valore associandolo tramite una chiave. La chiave di destinazione è chiamata encumberance (impedimento). Essa impone il requisito di una firma per poter riscattare i fondi in transazioni future. Gli output provenienti da una transazione possono essere usati come input di una nuova transazione, creando in questo modo una catena di proprietà nella quale la valuta è spostata da indirizzo a indirizzo (vedi Una catena di transazioni, dove l output di una transazione è l input della transazione successiva) 4

26 Figure 3. Transazioni come libro di contabilità in partita doppia 5

27 Figure 4. Una catena di transazioni, dove l output di una transazione è l input della transazione successiva Il pagamento di Alice al Bar di Bob utilizza una transazione precedente come input. Nel capitolo precedente Alice ha ricevuto bitcoin dal suo amico Joe in cambio di contanti. La transazione ha un numero di bitcoin bloccati attraverso la chiave di Alice. La sua nuova transazione al Bar di Bob fa riferimento alla transazione precedente come un input e crea nuovi output per pagare il caffè e per ricevere il resto. La transazioni formano una catena, nella quale gli input dell ultima transazione corrispondono agli output di transazioni precedenti. La chiave di Alice fornisce la firma che sblocca questi output delle transazioni precedenti, e quindi provando al network bitcoin che lei è la proprietaria dei fondi. Alice combina il pagamento per il caffè all indirizzo di Bob, in questo modo "blocca" l output con il requisito che Bob produca una firma per spendere quel valore. Questo rappresenta un trasferimento di valore da Alice a Bob. Questa catena di transazioni, da Joe a Alice a Bob, è illustrata in Una catena di transazioni, dove l output di una transazione è l input della transazione successiva. Forme di Transazioni Comuni La forma più comune di transazione è un semplice pagamento da un portafoglio ad un altro, che spesso include del "resto" che ritorna al proprietario originario. Questo tipo di transazione ha un imput e due outputs ed è illustrato in Transazioni più comuni. 6

28 Figure 5. Transazioni più comuni Un altra forma comune di transazione è quella che aggrega multipli input in un singolo output (vedi Transazioni aggregatrici). Questo rappresenta l equivalente nel mondo reale dello scambiare una pila di monete e banconote per una banconota singola di valore maggiore. Transazioni come queste sono talvolta generate da applicazioni wallet per "far pulizia" di transazioni di valore piccolo che sono state ricevute come resto dei precedenti pagamenti. 7

29 Figure 6. Transazioni aggregatrici Infine, un altra forma di transazione molto comune sul registro bitcoin è una transazione che distribuisce un input a piú di un output che rappresentano multipli destinatari (vedi [distribuzione delle transazioni]). Questo tipo di transazioni è talvolta usato da esercizi commerciali per distribuire i guadagni, ad esempio quando si fanno i pagamenti degli stipendi a vari dipendenti. Figure 7. Transazioni che distribuiscono fondi 8

30 Costruire una Transaction L applicazione wallet di alice contiene tutta la logica per selezionare gli appropriati input e output per costruire una transazione secondo le specifiche date da Alice. Alice deve solo specificare una destinazione e un importo e il resto accadrà nell applicazione wallet senza che lei ne veda i dettagli. Nota bene, un applicazione wallet può costruire transazioni anche essendo completamente offline. Come compilare e firmare un assegno a casa propria e inviarlo successivamente alla banca dentro una busta, la transazione non deve essere costruita e firmata mentre si è connessi alla rete bitcoin. Deve essere inviata al network eventualmente perchè sia eseguita. Ottenere gli Input Giusti Alice s wallet application will first have to find inputs that can pay for the amount she wants to send to Bob. Most wallet applications keep a small database of "unspent transaction outputs" that are locked (encumbered) with the wallet s own keys. Therefore, Alice s wallet would contain a copy of the transaction output from Joe s transaction, which was created in exchange for cash (see [getting_first_bitcoin]). A bitcoin wallet application that runs as a full-index client actually contains a copy of every unspent output from every transaction in the blockchain. This allows a wallet to construct transaction inputs as well as quickly verify incoming transactions as having correct inputs. However, because a full-index client takes up a lot of disk space, most user wallets run "lightweight" clients that track only the user s own unspent outputs. If the wallet application does not maintain a copy of unspent transaction outputs, it can query the bitcoin network to retrieve this information, using a variety of APIs available by different providers or by asking a full-index node using the bitcoin JSON RPC API. Ricerca tutti gli unspent output (output non spesi) per l indirizzo bitcoin di Alice shows a RESTful API request, constructed as an HTTP GET command to a specific URL. This URL will return all the unspent transaction outputs for an address, giving any application the information it needs to construct transaction inputs for spending. We use the simple command-line HTTP client curl to retrieve the response. Example 1. Ricerca tutti gli unspent output (output non spesi) per l indirizzo bitcoin di Alice $ curl 9

31 Example 2. Risposta della ricerca { "unspent_outputs":[ { } "tx_hash":"186f9f998a dd734d2804fe65fa35779", "tx_index": , "tx_output_n": 0, "script":"76a9147f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a888ac", "value": , "value_hex": " ", "confirmations":0 } ] La risposta nell'risposta della ricerca mostra un unspent output (un output che non è stato ancora speso) di proprietà dell indirizzo di Alice 1Cdid9KFAaatwczBwBttQcwXYCpvK8h7FK. La risposta include una referenza alla transazione nella quale questo unspent output è contenuto (il pagamento fatto da Joe) e il suo valore in satoshi, 10 milioni, equivalente a 0.10 bitcoin. Con questa informazione, l applicazione wallet di Alice può costruire la transazione per trasferire quel valore all indirizzo della nuova proprietaria. TIP Visualizza la transazione da Joe a Alice. As you can see, Alice s wallet contains enough bitcoins in a single unspent output to pay for the cup of coffee. Had this not been the case, Alice s wallet application might have to "rummage" through a pile of smaller unspent outputs, like picking coins from a purse until it could find enough to pay for coffee. In both cases, there might be a need to get some change back, which we will see in the next section, as the wallet application creates the transaction outputs (payments). Creare gli Output A transaction output is created in the form of a script that creates an encumbrance on the value and can only be redeemed by the introduction of a solution to the script. In simpler terms, Alice s transaction output will contain a script that says something like, "This output is payable to whoever can present a signature from the key corresponding to Bob s public address." Because only Bob has the wallet with the keys corresponding to that address, only Bob s wallet can present such a signature to redeem this output. Alice will therefore "encumber" the output value with a demand for a signature from Bob. 10

32 Questa transazione inoltre includerà un secondo output, visto che i fondi di Alice sono nella forma di un output di 0.10 BTC, troppi soldi per la tazza di caffè da BTC. Ad Alice spetteranno BTC di resto. Il pagamento per il resto di Alice è creato dal wallet di Alice proprio nella stessa transazione usata per il pagamento a Bob. Essenzialmente, il wallet di Alice divide i fondi in due pagamenti: uno a Bob, e uno indietro a se stessa. Alice può infine usare l output del resto in una transazione successiva, spendendolo in un secondo momento. Finally, for the transaction to be processed by the network in a timely fashion, Alice s wallet application will add a small fee. This is not explicit in the transaction; it is implied by the difference between inputs and outputs. If instead of taking in change, Alice creates only as the second output, there will be BTC (half a millibitcoin) left over. The input s 0.10 BTC is not fully spent with the two outputs, because they will add up to less than The resulting difference is the transaction fee that is collected by the miner as a fee for including the transaction in a block and putting it on the blockchain ledger. La transazione risultante può essere vista utilizzando un applicazione web blockchain explorer, come mostrato in La transazione di Alice al Bar di Bob. Figure 8. La transazione di Alice al Bar di Bob TIP Visualizza la transazione da Alice al Bar di Bob. Aggiungere la Transazione al Ledger (libro mastro) The transaction created by Alice s wallet application is 258 bytes long and contains everything necessary to confirm ownership of the funds and assign new owners. Now, the transaction must be 11

33 transmitted to the bitcoin network where it will become part of the distributed ledger (the blockchain). In the next section we will see how a transaction becomes part of a new block and how the block is "mined." Finally, we will see how the new block, once added to the blockchain, is increasingly trusted by the network as more blocks are added. Transmettendo la transaction Because the transaction contains all the information necessary to process, it does not matter how or where it is transmitted to the bitcoin network. The bitcoin network is a peer-to-peer network, with each bitcoin client participating by connecting to several other bitcoin clients. The purpose of the bitcoin network is to propagate transactions and blocks to all participants. Come si propaga Alice s wallet application can send the new transaction to any of the other bitcoin clients it is connected to over any Internet connection: wired, WiFi, or mobile. Her bitcoin wallet does not have to be connected to Bob s bitcoin wallet directly and she does not have to use the Internet connection offered by the cafe, though both those options are possible, too. Any bitcoin network node (other client) that receives a valid transaction it has not seen before will immediately forward it to other nodes to which it is connected. Thus, the transaction rapidly propagates out across the peer-to-peer network, reaching a large percentage of the nodes within a few seconds. Il Punto di Vista di Bob Se l applicazione wallet bitcoin di Bob è direttamente connessa all applicazione wallet di Alice, l applicazione wallet di Bob potrebbe essere il primo nodo a ricevere la transazione nel giro di pochi secondi. Il wallet di Bob identificherà immediatamente la transazione di Alice come un pagamento in ricezione perchè contiene output redimibile dalle chiavi di Bob. L applicazione wallet di Bob può anche indipendentemente verificare che la transazione sia formata correttamente, che utilizzi come input, i precedenti output non spesi, e che conttenga sufficenti fee di transazione per essere inclusa nel blocco successivo. A questo punto Bob può assumere, con poco rischio, che la transazione sarà nel giro di poco tempo inclusa in un blocco e confermata. TIP A common misconception about bitcoin transactions is that they must be "confirmed" by waiting 10 minutes for a new block, or up to 60 minutes for a full six confirmations. Although confirmations ensure the transaction has been accepted by the whole network, such a delay is unnecessary for small-value items such as a cup of coffee. A merchant may accept a valid small-value transaction with no confirmations, with no more risk than a credit card payment made without an ID or a signature, as merchants routinely accept today. Il Mining di Bitcoin La transazione è in questo modo propagata sulla rete bitcoin. Non entra a far parte del libro mastro condiviso (la blockchain) fino a che non è verificata e inclusa in un blocco da un processo chiamato 12

34 mining. Vedi il [ch8] per una spiegazione più dettagliata. Il sistema della fiducia usato da bitcoin è basato sulla computazione. Le transazioni sono raggruppate in blocchi, che richiedono un enorme quanità di potenza computazionale per essere verificate come valide. Il processo di mining in bitcoin serve a due scopi: Il Mining crea nuovi bitcoin per ogni blocco, quasi come una banca centrale emette nuova moneta. La quantità di bitcoin creata per blocco è fissa e diminuisce col tempo. Il Mining crea fiducia assicurando che le transazioni siano confermate solo se è stata usata sufficiente potenza di calcolo per il blocco che le contiene. Un maggior numero di blocchi richiede una maggiore potenza di calcolo, questo processo assicura una fiducia maggiore. A good way to describe mining is like a giant competitive game of sudoku that resets every time someone finds a solution and whose difficulty automatically adjusts so that it takes approximately 10 minutes to find a solution. Imagine a giant sudoku puzzle, several thousand rows and columns in size. If I show you a completed puzzle you can verify it quite quickly. However, if the puzzle has a few squares filled and the rest are empty, it takes a lot of work to solve! The difficulty of the sudoku can be adjusted by changing its size (more or fewer rows and columns), but it can still be verified quite easily even if it is very large. The "puzzle" used in bitcoin is based on a cryptographic hash and exhibits similar characteristics: it is asymmetrically hard to solve but easy to verify, and its difficulty can be adjusted. In [user-stories], we introduced Jing, a computer engineering student in Shanghai. Jing is participating in the bitcoin network as a miner. Every 10 minutes or so, Jing joins thousands of other miners in a global race to find a solution to a block of transactions. Finding such a solution, the so-called proof of work, requires quadrillions of hashing operations per second across the entire bitcoin network. The algorithm for proof of work involves repeatedly hashing the header of the block and a random number with the SHA256 cryptographic algorithm until a solution matching a predetermined pattern emerges. The first miner to find such a solution wins the round of competition and publishes that block into the blockchain. Jing started mining in 2010 using a very fast desktop computer to find a suitable proof of work for new blocks. As more miners started joining the bitcoin network, the difficulty of the problem increased rapidly. Soon, Jing and other miners upgraded to more specialized hardware, such as high-end dedicated graphical processing units (GPUs) cards such as those used in gaming desktops or consoles. At the time of this writing, the difficulty is so high that it is profitable only to mine with applicationspecific integrated circuits (ASIC), essentially hundreds of mining algorithms printed in hardware, running in parallel on a single silicon chip. Jing also joined a "mining pool," which much like a lottery pool allows several participants to share their efforts and the rewards. Jing now runs two USBconnected ASIC machines to mine for bitcoin 24 hours a day. He pays his electricity costs by selling the bitcoin he is able to generate from mining, creating some income from the profits. His computer runs a copy of bitcoind, the reference bitcoin client, as a backend to his specialized mining software. 13

35 Effettuare Mining delle Transazioni presenti nei Blocchi A transaction transmitted across the network is not verified until it becomes part of the global distributed ledger, the blockchain. Every 10 minutes on average, miners generate a new block that contains all the transactions since the last block. New transactions are constantly flowing into the network from user wallets and other applications. As these are seen by the bitcoin network nodes, they get added to a temporary pool of unverified transactions maintained by each node. As miners build a new block, they add unverified transactions from this pool to a new block and then attempt to solve a very hard problem (a.k.a., proof of work) to prove the validity of that new block. The process of mining is explained in detail in [mining]. Transactions are added to the new block, prioritized by the highest-fee transactions first and a few other criteria. Each miner starts the process of mining a new block of transactions as soon as he receives the previous block from the network, knowing he has lost that previous round of competition. He immediately creates a new block, fills it with transactions and the fingerprint of the previous block, and starts calculating the proof of work for the new block. Each miner includes a special transaction in his block, one that pays his own bitcoin address a reward of newly created bitcoins (currently 25 BTC per block). If he finds a solution that makes that block valid, he "wins" this reward because his successful block is added to the global blockchain and the reward transaction he included becomes spendable. Jing, who participates in a mining pool, has set up his software to create new blocks that assign the reward to a pool address. From there, a share of the reward is distributed to Jing and other miners in proportion to the amount of work they contributed in the last round. La transazione di Alice è stata raccolta dalla rete e inclusa nel gruppo di transazioni non ancora verificate. Visto che aveva una commissione sufficiente, è stata inclusa in un blocco generato dalla mining pool di Jing. Approssimativamente cinque minuti dopo che la transazione è stata trasmessa dal wallet di Alice, l ASIC miner di Jing ha trovato una soluzione per il blocco e ha pubblicato il blocco #277316, contenente 419 altre transazioni. Il miner ASIC di Jing ha pubblicato il nuovo blocco sul network bitcoin, dove altri miner lo hanno validato e hanno iniziato la competizione per generare il blocco successivo. E' possibile visionare il blocco che include la transazione di Alice. Qualche minuto dopo, un nuovo blocco, #277317, è confermato tramite il lavoro di mining di un altro miner. Visto che questo nuovo blocco è basato sul blocco precedente (#277316) che conteneva la transazione di Alice, ha aggiunto una grande quantità di computazione su quel blocco, rafforzando in questo modo la fiducia in quelle transazioni. Il blocco contenente le transazioni di Alice è contato come una "conferma" di quella transazione. Ogni blocco su cui è effettuato mining sopra di quello contenente la transazione è una conferma addizionale. Man mano che i blocchi si impilano uno sopra l altro, diventa esponenzialmente più difficile invertire la transazione, in questo modo rendendo il network sempre più sicuro. In the diagram in La transazione di Alice inclusa nel blocco # we can see block #277316, which contains Alice s transaction. Below it are 277,316 blocks (including block #0), linked to each other in a chain of blocks (blockchain) all the way back to block #0, known as the genesis block. Over time, as the 14

36 "height" in blocks increases, so does the computation difficulty for each block and the chain as a whole. The blocks mined after the one that contains Alice s transaction act as further assurance, as they pile on more computation in a longer and longer chain. By convention, any block with more than six confirmations is considered irrevocable, because it would require an immense amount of computation to invalidate and recalculate six blocks. We will examine the process of mining and the way it builds trust in more detail in [ch8]. Figure 9. La transazione di Alice inclusa nel blocco #

37 Spendere la Transaction Now that Alice s transaction has been embedded in the blockchain as part of a block, it is part of the distributed ledger of bitcoin and visible to all bitcoin applications. Each bitcoin client can independently verify the transaction as valid and spendable. Full-index clients can track the source of the funds from the moment the bitcoins were first generated in a block, incrementally from transaction to transaction, until they reach Bob s address. Lightweight clients can do what is called a simplified payment verification (see [spv_nodes]) by confirming that the transaction is in the blockchain and has several blocks mined after it, thus providing assurance that the network accepts it as valid. Bob a questo punto può spendere l output da questa e da altre transazioni, creando la sua transazione che referenzia questi output come loro input e li rende propri (gli assegna la ownership). Per esempio, Bob può pagare un cliente o fornitore trasferendo valore dal pagamento del caffè a questi nuovi proprietari. Più probabilmente, il software di bitcoin di Bob aggregherà molti pagamenti piccoli in un pagamento più grande, probabilmente concentrando tutto il guadagno dei bitcoin del giorno in un unica transazione. Questo muoverà i vari pagamenti verso un singolo indirizzo, usato come account "bancario" generico (checking account). Per vedere un diagramma di aggregazione di transazione, vedi Transazioni aggregatrici (aggregazione in una transazione). Non appena Bob spende i pagamenti ricevuti da Alice e da altri clienti, egli estende la catena delle transazioni, le quali all indietro sono aggiunte alla ledger (libro mastro) globale di modo che tutti possano vedere e fidarcisi. Assumiamo che Bob paghi il suo web designer Gopesh a Bangalore per una nuova pagina web del suo sito. Adesso la catena di transazioni assomiglierà a La transazione di Alice come parte di una catena di transazioni da Joe a Gopesh. 16

38 Figure 10. La transazione di Alice come parte di una catena di transazioni da Joe a Gopesh 17

39 Il Client Bitcoin Bitcoin Core: L Implementazione di Riferimento Puoi scaricare il client di riferimento Bitcoin Core, conosciuto anche come "Satoshi client" da bitcoin.org. Il client di riferimento implementa tutti gli aspetti del sistema bitcoin, questo include i wallet, un motore di verifica delle transazioni con una copia completa dell intero registro delle transazioni (blockchain) e un nodo completo nella rete peer-to-peer bitcoin. Suhttp://bitcoin.org/en/choose-your-wallet[Pagina Scegli il tuo Wallet del sito Bitcoin org], seleziona Bitcoin Core per scaricare il client di riferimento. A seconda del tuo sistema operativo, scaricherai un installer eseguibile. Per windows, questo sarà un archivio ZIP o un eseguibile.exe. Per Mac OS è un immagine disco.dmg. Le versioni di Linux includono un pacchetto PPA per ubuntu o un archivio tar.gz. La pagina bitcoin.org che elenca i client bitcoin consigliati è mostrata in Scegliendo un client bitcoin su bitcoin.org Figure 1. Scegliendo un client bitcoin su bitcoin.org Eseguire Bitcoin Core per la Prima Volta Se stai scaricando un pacchetto installabile, come un.exe,.dmg, o PPA, potrai installarle nello stesso modo un applicazione sul tuo sistema operativo. Per Windows, esegui l'.exe e segui le istruzioni passoper-passo. Per Mac OS, lancia il.dmg e sposta l icona di Bitcoin-QT nella tua cartella Applicazioni. Per Ubuntu, clicca due volte sul PPA nel tuo File Explorer e questo aprirà il package manager per installare il pacchetto. Una volta completata l installazione dovresti avere una nuova applicazione chiamata Bitcoin-QT tra la lista delle tue applicazioni attualmente installate. Clicca due volte l icona per avviare il client bitcoin. La prima volta quando esegui Bitcoin Core, inizierà a scaricare la blockchain, un processo che potrebbe impiegare qualche giorno (vedi Scharmata di Bitcoin Core durante l inizializzazione della blockchain). Lascialo girare in background fino a che non mostrerà "Synchronized" (Sincronizzato) e non "out of sync" accanto al balance (saldo). 1

40 Figure 2. Scharmata di Bitcoin Core durante l inizializzazione della blockchain TIP Il Bitcoin Core mantiene una copia completa di tutto il libro mastro delle transazioni (blockchain), con tutte le transazioni che sono avvenute nelle rete bitcoin fin dall inizio nel Questo dataset ha una dimensione di svariati gigabytes (approssimativamente 16 GB a fine 2013) ed è scaricato in modo incrementale in più giorni. Il client non sarà in grado di processare transazioni o aggiornare il saldo del conto affinché il dataset della blockchain non è scaricato completamente. Durante questo periodo, il client mostrerà la scritta "non sincronizzato" vicino al saldo del conto e "sincronizzazione in corso" nel footer. Assicurarsi di avere sufficiente spazio nel disco, larghezza di banda, e tempo per completare la sincronizzazione iniziale Compilare Bitcoin Core dal Codice Sorgente Per gli sviluppatori, c è anche l opzione di scaricare il codice sorgente completo come un file ZIP o clonare il sorgente principale dal repository presente su GitHub. Sulla pagina bitcoin/bitcoin su GitHub, seleziona Download ZIP dalla barra in alto. In alternativa, utilizza il comando git da terminale per creare una copia locale del codice sorgente sulla tua macchina. Nell esempio seguente, stiamo clonando il codice sorgente da riga di comando Unix, presente in Linux e Mac OS. 2

41 $ git clone Cloning into 'bitcoin'... remote: Counting objects: 31864, done. remote: Compressing objects: 100% (12007/12007), done. remote: Total (delta 24480), reused (delta 19621) Receiving objects: 100% (31864/31864), MiB 119 KiB/s, done. Resolving deltas: 100% (24480/24480), done. $ TIP Le istruzioni e l output ritornato potrebbero variare da una versione all altra. Segui la documentazione fornita con il codice anche se differisce dalle istruzioni riportate qui, e non sorprenderti se l output mostrato sul tuo schermo è leggermente differente dagli esempi riportati di seguito. Non appena l operazione di git clone sarà completata, avrai una copia locale completa del repository del codice nella directory bitcoin. Entra dentro questa directory digitando cd bitcoin nel prompt/terminale: $ cd bitcoin Come default, la copia locale sarà sincronizzare con il codice più recente, che potrebbe essere una versione beta o unsable di bitcoin. Prima di compilare il codice, seleziona una versione specifica facendo il checkout di un release tag. Questo farà sincronizzare la copia locale con la versione specifica del codice del repository identificato con un etichetta detta tag. I tag sono usati dai developer per segnare release specifiche del codice per numero di versione. Per prima cosa, per trovare la lista di tutti i tag disponibili, utilizzeremo il comando git tag: $ git tag v0.1.5 v0.1.6test1 v0.2.0 v v v [... molti altri tag...] v0.8.4rc2 v0.8.5 v0.8.6 v0.8.6rc1 v0.9.0rc1 3

42 La lista dei tag mostra tutte le versioni di bitcoin rilasciate. Per convenzione, le release candidate, che sono fatte per testing, hanno il suffisso "rc". Le release stabili (stable) che possono essere eseguite su sistemi in produzione non hanno suffisso. Dalla lista precedente, seleziona la versione di release maggiore, che è v0.9.0rc1 al momento della scrittura di questo libro. Per sincronizzare il codice locale con questa versione, utilizza il comando git checkout: $ git checkout v0.9.0rc1 Note: checking out 'v0.9.0rc1'. HEAD is now at 15ec Merge pull request #3605 $ Il codice sorgente include la documentazione, che può essere trovata in un numero di file. Controlla la documentazione principale che si trova nel README.md nella directory bitcoin digitando more README.md nel prompt e usando la barra spaziatrice per procedere alla pagina successiva. In questo capitolo, compileremo il bitcoin client da riga di comando, anche conosciuto come bitcoind su Linux. Ricontrolla le istruzioni per compilare il client da riga di comando bitcoind per la tua distribuzione digitando more doc/build-unix.md. Istruzioni alternative per Mac OS X e Windows sono disponibili nella directory doc, rispettivamente in build-osx.md o build-msw.md. Revisiona attentamente i requisiti di build, che sono nella prima parte della documentazione della build. Queste sono le librerie che devono essere presenti sul tuo sistema prima che tu possa iniziare a compilare bitcoin. Se questi prerequisiti non sono presenti, il processo di build fallirà con un errore. Se questo avviene perchè ti manca un prerequisito, puoi installarlo e poi continuare il processo di build da dove eri rimasto. Assumendo che i prerequisiti siano installati, inizierai il processo di build generando una serie di script di build usando lo script autogen.sh. TIP Il processo di build di Bitcoin Core è stato modificato perchè utilizzi il sistema di autogen/configure/make dalla versione 0.9. Versioni precedenti utilizzavano un semplice Makefile e funzionavano in modo leggermente differente dal seguente esempio. Segui le istruzioni per la versione che vuoi compilare. L autogen/configure/make introdotto nella 0.9 sarà probabilmente il build system utilizzato per tutte le versioni future del codice e è il sistema mostrato nei seguenti esempi. $./autogen.sh configure.ac:12: installing `src/build-aux/config.guess' configure.ac:12: installing `src/build-aux/config.sub' configure.ac:37: installing `src/build-aux/install-sh' configure.ac:37: installing `src/build-aux/missing' src/makefile.am: installing `src/build-aux/depcomp' $ Lo script autogen.sh crea una serie di script di configurazione automatici che interrogheranno il tuo 4

43 sistema per scoprire i settaggi corretti e che assicureranno che tu abbia tutte le librerie necessarie per compilare il codice. La cosa più importante di queste è che lo script di configure offre una serie di opzioni differenti per personalizzare il processo di build. Digita./configure --help per vedere tutte le opzioni disponibili: $./configure --help `configure' configures Bitcoin Core to adapt to many kinds of systems. ('configure' configura Bitcoin Core per adattarlo a diversi tipi di sistemi.) Usage (Utilizzo):./configure [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as (Per assegnare variabili d'ambiente - specificale come) VAR=VALUE. See below for descriptions of some of the useful variables. (Vedi di seguito per una descrizione delle variabili utili.) Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit (mostra questo messaggio di aiuto e esce) --help=short display options specific to this package (mostra le opzioni specifiche di questo pacchetto) --help=recursive display the short help of all the included packages (mostra il testo di aiuto di tutti i pacchetti inclusi) -V, --version display version information and exit (mostra le informazioni di versione) [... moltre altre opzioni e variabili saranno mostrate di seguente...] Funzionalità Opzionali: --disable-option-checking ignore unrecognized --enable/--with options --disable-feature do not include FEATURE (same as --enable-feature=no) (non includere la funzionalità FEATURE) --enable-feature[=arg] include FEATURE [ARG=yes] [... altre opzioni...] Utilizza queste variabili per sovrascrivere le scelte fatte da `configure` o per facilitare la possibilità di caricare librerie e programmi con nomi/percorsi non standard. Comunica i bug a <[email protected]>. $ 5

44 Lo script configure permette di abilitare o disabilitare alcune funzioni di bitcoind attraverso l uso dei flag --enable-feature e --disable-feature, nei quali FEATURE è sostituita dal nome della funzionalità da abilitare/disabilitare, come listato nell output del comando help. In questo capitolo, compileremo il client bitcoind con tutte le funzionalità di base. Non useremo i flag di configurazione, ma dovresti ricontrollarli per capire quali funzionalità opzionali fanno parte del client. Poi, esegui lo script configure per scoprire automaticamente tutte le librerie necessarie e per creare uno script di compilazione customizzato per il tuo sistema: $./configure checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes [... molte altre funzionalità del sistema sono testate...] configure: creating./config.status config.status: creating Makefile config.status: creating src/makefile config.status: creating src/test/makefile config.status: creating src/qt/makefile config.status: creating src/qt/test/makefile config.status: creating share/setup.nsi config.status: creating share/qt/info.plist config.status: creating qa/pull-tester/run-bitcoind-for-test.sh config.status: creating qa/pull-tester/build-tests.sh config.status: creating src/bitcoin-config.h config.status: executing depfiles commands $ Se tutto va bene, il comando configure terminerà creando gli script di build personalizzati che ci permetteranno di compilare bitcoind. Se qualche libreria è mancante o se ci sono errori, il comando configure terminerà con un errore invece di creare gli script di build. Se un errore viene riportato, sarà probabilmente perchè ti manca una libreria o c è una libreria non compatibile. Ricontrolla nuovamente la documentazione di build e sii sicuro di aver installato tutti i prerequisiti mancanti. A questo punto lancia configure nuovamente e ricontrolla se l errore sia stato risolto. Infine, compilerai il codice sorgente, un processo che potrà impiegare fino a un ora per essere completato. Durante il processo di compilazione potrai vedere output entro pochi secondi o entro pochi minuti, o un errore se qualcosa va storto. Il processo di compilazione può essere avviato nuovamente in qualsiasi momento se per qualche ragione viene interrotto. Digita make per iniziare a compilare: 6

45 $ make Making all in src make[1]: Entering directory `/home/ubuntu/bitcoin/src' make all-recursive make[2]: Entering directory `/home/ubuntu/bitcoin/src' Making all in. make[3]: Entering directory `/home/ubuntu/bitcoin/src' CXX addrman.o CXX alert.o CXX rpcserver.o CXX bloom.o CXX chainparams.o [... seguono molti altri messaggi di compilazione...] CXX test_bitcoin-wallet_tests.o CXX test_bitcoin-rpc_wallet_tests.o CXXLD test_bitcoin make[4]: Leaving directory `/home/ubuntu/bitcoin/src/test' make[3]: Leaving directory `/home/ubuntu/bitcoin/src/test' make[2]: Leaving directory `/home/ubuntu/bitcoin/src' make[1]: Leaving directory `/home/ubuntu/bitcoin/src' make[1]: Entering directory `/home/ubuntu/bitcoin' make[1]: Nothing to be done for `all-am'. make[1]: Leaving directory `/home/ubuntu/bitcoin' $ Se tutto è andato bene, bitcoind dovrebbe essere compilato. Il passo finale a questo punto è installare l eseguibile bitcoind nel sistema usando il comando make: $ sudo make install Making install in src Making install in. /bin/mkdir -p '/usr/local/bin' /usr/bin/install -c bitcoind bitcoin-cli '/usr/local/bin' Making install in test make install-am /bin/mkdir -p '/usr/local/bin' /usr/bin/install -c test_bitcoin '/usr/local/bin' $ Puoi confermare che bitcoin è correttamente installato chiedendo al sistema il percorso dei due eseguibili, come di seguito: 7

46 $ which bitcoind /usr/local/bin/bitcoind $ which bitcoin-cli /usr/local/bin/bitcoin-cli L installazione di bitcoind di default lo metterà in /usr/local/bin. Quando lancerai bitcoind per la prima volta, ti ricorderà di creare un file di configurazione con una strong password (una password abbastanza complessa e quindi sicura) per l interfaccia JSON-RPC. Esegui bitcoind digitando bitcoind nel terminale: $ bitcoind Errore: Per utilizzare l'opzione "-server", dovrai impostare una rpcpassword nel file di configurazione: /home/ubuntu/.bitcoin/bitcoin.conf E' consigliato usare la seguente password casuale: rpcuser=bitcoinrpc rpcpassword=2xa4dukncbtzxsbqrrndewey2nm6m4h9tx5dfjoavvbk (non c'è bisogno che ti ricordi questa password) L'username e la password NON DEVONO essere uguali. Se il file non esiste, crealo con i permessi owner-readable-only (leggibile solo dal proprietario). E' inoltre consigliato impostare alertnotify di modo da essere notificato riguardo eventuali problemi; per esempio: alertnotify=echo %s mail -s "Bitcoin Alert" [email protected] Modifica il file di configurazione nel tuo editor preferito e imposta i parametri, sostituisci la password con una password sicura (strong password) come ti raccomandano le istruzioni di bitcoind. Non usare la password mostrata di seguito. Crea il file dentro la directory.bitcoin_di modo che il percorso finale sia _.bitcoin/bitcoin.conf e imposta un username e una password: rpcuser=bitcoinrpc rpcpassword=2xa4dukncbtzxsbqrrndewey2nm6m4h9tx5dfjoavvbk Mentre stai modificando questo file di configurazione, probabilmente vorrai impostare alcune opzioni in più, come txindex (vedi Indice del Database delle Transazioni e Opzione txindex). Per una lista completa delle opzioni disponibili, digita bitcoind --help. A questo punto, esegui il client Bitcoin Core. La prima volta che verrà eseguito, ricostruirà la blockchain di bitcoin scaricando tutti i blocchi. Questo è un file di molti gigabyte e richiederà una media di tre giorni per essere completamente scaricato. Potrai accorciare il tempo di inizializzazione della blockchain scaricando una copia parziale della blockchain usando un client BitTorrent scaricabile da SourceForge. 8

47 Esegui bitcoind in background con l opzione -daemon: $ bitcoind -daemon Bitcoin version v0.9.0rc1-beta ( :30: ) Using OpenSSL version OpenSSL 1.0.1c 10 May 2012 Default data directory /home/bitcoin/.bitcoin Using data directory /bitcoin/ Using at most 4 connections (1024 file descriptors available) init message: Verifying wallet... dbenv.open LogDir=/bitcoin/database ErrorFile=/bitcoin/db.log Bound to [::]:8333 Bound to :8333 init message: Loading block index... Opening LevelDB in /bitcoin/blocks/index Opened LevelDB successfully Opening LevelDB in /bitcoin/chainstate Opened LevelDB successfully [... altri messaggi d'avvio...] Utilizzando la API JSON-RPC di Bitcoin Core dalla Riga di Comando Il Core Client Bitcoin implementa un interfaccia JSON-RPC a cui si può accedere anche utilizzando il programma da riga di comando bitcoin-cli. La riga di comando (detta anche terminale o shell) ci permette di sperimentare interattivamente con tutte le potenzialità che sono anche disponibili attraverso l API. Per cominciare, invoca il comando help per visualizzare una lista dei comandi bitcoin RPC disponibili: $ bitcoin-cli help addmultisigaddress nrequired ["key",...] ( "account" ) addnode "node" "add remove onetry" backupwallet "destination" createmultisig nrequired ["key",...] createrawtransaction [{"txid":"id","vout":n},...] {"address":amount,...} decoderawtransaction "hexstring" decodescript "hex" dumpprivkey "bitcoinaddress" dumpwallet "filename" getaccount "bitcoinaddress" getaccountaddress "account" getaddednodeinfo dns ( "node" ) getaddressesbyaccount "account" 9

48 10 getbalance ( "account" minconf ) getbestblockhash getblock "hash" ( verbose ) getblockchaininfo getblockcount getblockhash index getblocktemplate ( "jsonrequestobject" ) getconnectioncount getdifficulty getgenerate gethashespersec getinfo getmininginfo getnettotals getnetworkhashps ( blocks height ) getnetworkinfo getnewaddress ( "account" ) getpeerinfo getrawchangeaddress getrawmempool ( verbose ) getrawtransaction "txid" ( verbose ) getreceivedbyaccount "account" ( minconf ) getreceivedbyaddress "bitcoinaddress" ( minconf ) gettransaction "txid" gettxout "txid" n ( includemempool ) gettxoutsetinfo getunconfirmedbalance getwalletinfo getwork ( "data" ) help ( "command" ) importprivkey "bitcoinprivkey" ( "label" rescan ) importwallet "filename" keypoolrefill ( newsize ) listaccounts ( minconf ) listaddressgroupings listlockunspent listreceivedbyaccount ( minconf includeempty ) listreceivedbyaddress ( minconf includeempty ) listsinceblock ( "blockhash" target-confirmations ) listtransactions ( "account" count from ) listunspent ( minconf maxconf ["address",...] ) lockunspent unlock [{"txid":"txid","vout":n},...] move "fromaccount" "toaccount" amount ( minconf "comment" ) ping sendfrom "fromaccount" "tobitcoinaddress" amount ( minconf "comment" "comment-to" ) sendmany "fromaccount" {"address":amount,...} ( minconf "comment" ) sendrawtransaction "hexstring" ( allowhighfees ) sendtoaddress "bitcoinaddress" amount ( "comment" "comment-to" )

49 setaccount "bitcoinaddress" "account" setgenerate generate ( genproclimit ) settxfee amount signmessage "bitcoinaddress" "message" signrawtransaction "hexstring" ( [{"txid":"id","vout":n,"scriptpubkey":"hex","redeemscript":"hex"},...] ["privatekey1",...] sighashtype ) stop submitblock "hexdata" ( "jsonparametersobject" ) validateaddress "bitcoinaddress" verifychain ( checklevel numblocks ) verifymessage "bitcoinaddress" "signature" "message" walletlock walletpassphrase "passphrase" timeout walletpassphrasechange "oldpassphrase" "newpassphrase" Ottenendo Informazioni sullo Stato del Client Bitcoin Core Commands: getinfo Il comando RPC di Bitcoin getinfo mostra informazioni base riguardo lo stato del nodo bitcoin del network, del wallet, e del database blockchain. Utilizza bitcoin-cli per eseguirlo: $ bitcoin-cli getinfo { } "version" : 90000, "protocolversion" : 70002, "walletversion" : 60000, "balance" : , "blocks" : , "timeoffset" : -72, "connections" : 4, "proxy" : "", "difficulty" : , "testnet" : false, "keypoololdest" : , "keypoolsize" : 101, "paytxfee" : , "errors" : "" I dati sono ritornati in JavaScript Object Notation (JSON), un formato che può facilmente essere "consumato" da tutti i linguaggi di programmazione, ma che è anche abbastanza leggibile dall utente. 11

50 Oltre a questi dati vedremo i numeri di versione per il client (90000), del protocollo (70002), e infine del wallet (60000). Possiamo vedere il balance attuale contenuto nel wallet, che attualmente è zero. Possiamo notare la block height attuale, che mostra quanti blocchi sono presenti, secondo il client (286216). Possiamo inoltre notare varie statistiche riguardo il network bitcoin e le impostazioni relative a questo client. Esploreremo queste impostazioni in maggiore dettaglio nel corso di questo capitolo. TIP Ci vorrà qun po' di tempo, probabilmente più di un giorno, prima che bitcoind "raggiunga" l altezza attuale della blockchain mentre scarica i blocchi da altri client bitcoin. Puoi controllare il progresso usando getinfo per vedere il numero di blocchi conosciuti. Setup del Wallet e Encryption (Protezione Crittografica) Comandi: encryptwallet, walletpassphrase Prima di procedere nel generare chiavi e altri comandi, dovresti per prima cosa criptare il wallet con una password. Per questo esempio, utilizzerai il comando encryptwallet con la password "foo". Ovviamente, sostituisci "foo" con una password più complessa e strong! $ bitcoin-cli encryptwallet foo wallet criptato; Il server di bitcoin si fermerà, si riavvierà per eseguire il wallet encrypted. La keypool è stata refreshata, dovrai effettuare un nuovo backup. $ Puoi verificare che il wallet sia stato criptato lanciando nuovamente il comando getinfo. Questa volta noterai un nuovo elemento chiamato unlocked_until. Questo è un contatore che mostra per quanto tempo il processo di decriptazione della password del wallet sarà salvato in memoria, mantenendo il wallet aperto. All inizio questo valore sarà impostato a zero, che sta a significare che il wallet è chiuso (protetto). $ bitcoin-cli getinfo { "version" : 90000, #[... altre informazioni...] } $ "unlocked_until" : 0, "errors" : "" 12

51 Per sbloccare il wallet, digita il comando walletpassphrase, che prende due parametri la password ed un numero di secondi fino a quando il wallet sarà di nuovo bloccato automaticamente (un contatore): $ bitcoin-cli walletpassphrase foo 360 $ Potrai confermare che il wallet è sbloccato e vedere il timeout eseguendo nuovamente getinfo: $ bitcoin-cli getinfo { "version" : 90000, #[... altre informazioni...] } "unlocked_until" : , "errors" : "" Backup del Wallet, Dump Plain-text, e Restore Comandi: backupwallet, importwallet, dumpwallet A questo punto, faremo un po di pratica nel creare un file di backup del wallet e poi effettueremo il ripristino del wallet dal file di backup. Utilizza il comando backupwallet per effettuare il backup, fornendo come parametro il nome del file. In questo esempio effettuiamo il backup del wallet nel file wallet.backup: $ bitcoin-cli backupwallet wallet.backup $ A questo punto, esegui il ripristino del tuo file di backup, usa il comando importwallet. Se il tuo wallet è protetto (locked), dovrai prima effettuare l unlock (vedi walletpassphrase nella sezione precedente) per importare il file di backup: $ bitcoin-cli importwallet wallet.backup $ Il comando dumpwallet può essere utilizzato per fare il dump del wallet in un file di testo che sia leggibile dall utente (human-readable): 13

52 $ bitcoin-cli dumpwallet wallet.txt $ more wallet.txt # Wallet dump created by Bitcoin v0.9.0rc1-beta ( :30: ) # * Created on dT20:34:55Z # * Best block at time of backup was ( f74f0bc9d3c186267bc45c7b91c49a ac24c0d3a44), # mined on dT20:24:01Z KzTg2wn6Z8s7ai5NA9MVX4vstHRsqP26QKJCzLg4JvFrp6mMaGB dT04:30:27Z change=1 # addr=16pj6xkwsqv5ma5fsxmrpaxeyrenceg47f Kz3dVz7R6mUpXzdZy4gJEVZxXJwA15f198eVui4CUivXotzLBDKY dT04:30:27Z change=1 # addr=17ojds8kan8lp8kuakwtco6zm7bgxfc3gk [... molte altre chiavi...] $ Indirizzi del Wallet e Ricezione delle Transazioni Comandi: getnewaddress, getreceivedbyaddress, listtransactions, getaddressesbyaccount, getbalance The bitcoin reference client maintains a pool of addresses, the size of which is displayed by keypoolsize when you use the command getinfo. These addresses are generated automatically and can then be used as public receiving addresses or change addresses. To get one of these addresses, use the getnewaddress command: $ bitcoin-cli getnewaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL Ora, possiamo utilizzare questo indirizzo per inviare una piccola somma di bitcoin al nostro wallet bitcoind da un wallet esterno (assumendo che tu abbia qualche bitcoin in un exchange, wallet web, o un altro wallet bitcoin da qualche parte). Per questo esempio, invieremo 50 millibit (0.050 bitcoin) all indirizzo precedente. Possiamo ora interrogare il client bitcoind per il valore ricevuto da questo indirizzo, e specificare quante conferme sono necessarie prima che il valore sia incluso nel balance. Per questo esempio, specificheremo zero conferme. Pochi secondi dopo aver inviato i bitcoin da un altro wallet, vedremo il cambio di stato nel wallet. Utilizzeremo getreceivedbyaddress con il nuovo indirizzo e il numero di conferme impostato a zero (0): $ bitcoin-cli getreceivedbyaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL Se omettiamo lo zero dalla fine di questo comando, vedremo solo i valori che hanno almeno minconf 14

53 conferme, dove minconf è l impostazione per il numero minimo di conferme prima che una transazione vada a far parte del balance. L impostazione minconf è specificata nel file di configurazione bitcoind. Visto che la transazione che sta inviando questi bitcoin è trasmessa solo da pochi secondi, non sarà ancora stata confermata e quindi vedremo un balance di zero: $ bitcoin-cli getreceivedbyaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL Le transazioni ricevute dal wallet possono essere mostrate usando il comando listtransactions: $ bitcoin-cli listtransactions [ ] { } "account" : "", "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "category" : "receive", "amount" : , "confirmations" : 0, "txid" : "9ca8f969bd3ef5ec2a fdbf7a8bd365524c2e1fc66c309acbae2c14ae3", "time" : , "timereceived" : Possiamo listare tutti gli indirizzi presenti nel wallet usando il comando getaddressesbyaccount: $ bitcoin-cli getaddressesbyaccount "" 15

54 [ ] "1LQoTPYy1TyERbNV4zZbhEmgyfAipC6eqL", "17vrg8uwMQUibkvS2ECRX4zpcVJ78iFaZS", "1FvRHWhHBBZA8cGRRsGiAeqEzUmjJkJQWR", "1NVJK3JsL41BF1KyxrUyJW5XHjunjfp2jz", "14MZqqzCxjc99M5ipsQSRfieT7qPZcM7Df", "1BhrGvtKFjTAhGdPGbrEwP3xvFjkJBuFCa", "15nem8CX91XtQE8B1Hdv97jE8X44H3DQMT", "1Q3q6taTsUiv3mMemEuQQJ9sGLEGaSjo81", "1HoSiTg8sb16oE6SrmazQEwcGEv8obv9ns", "13fE8BGhBvnoy68yZKuWJ2hheYKovSDjqM", "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "1KHUmVfCJteJ21LmRXHSpPoe23rXKifAb2", "1LqJZz1D9yHxG4cLkdujnqG5jNNGmPeAMD" Finally, the command getbalance will show the total balance of the wallet, adding up all transactions confirmed with at least minconf confirmations: $ bitcoin-cli getbalance TIP Se la transazione non è ancora confermata, il saldo ritornato da getbalance sarà zero. L opzione di configurazione "minconf" determina il numero minimo di conferme necessarie prima che una transazione venga inclusa nel saldo. Esplorando e Decodificando le Transazioni Comandi: gettransaction, getrawtransaction, decoderawtransaction Esploreremo la transazione in entrata che è stata listata precedentemente utilizzando il comando gettransaction. Possiamo recuperare una transazione tramite il suo hash di transazione, mostrato precedentemente come txid, con il comando gettransaction: 16

55 { } "amount" : , "confirmations" : 0, "txid" : "9ca8f969bd3ef5ec2a fdbf7a8bd365524c2e1fc66c309acbae2c14ae3", "time" : , "timereceived" : , "details" : [ { "account" : "", "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "category" : "receive", "amount" : } ] TIP Gli ID di transazione non sono autoritativi fino a che una transazione non è confermata. L assenza di un hash di transazione nella blokchain non significa che la transazione non sia stata processata. Questo è conosciuto come "transaction malleability," malleabilità di transazione, perchè gli hash di transazione possono essere modificate prima di essere confermati in un blocco. Dopo essere stati confermati, i txid sono immutabili e autoritativi. La rappresentazione di una transazione come mostrata dal comando gettransaction è nella forma semplificata. Per ottenere il codice di transazione completo e decodificarlo, utilizzeremo due comandi: getrawtransaction e decoderawtransaction. Per primo, getrawtransaction prende come parametro l'hash di transazione (txid) e ritorna la transazione completa come stringa "raw" esadecimale, esattamente nella stessa forma come quella esistente sul network bitcoin: Per decodificare questa stringa esadecimale, utilizziamo il comando decoderawtransaction. Copia e incolla l esadecimale come primo parametro di decoderawtransaction per ottenere il contenuto completo interpretato come struttura dati JSON (per ragioni di formattazione la stringa esadecimale del seguente esempio è stata troncata): La decodifica della transazione mostra tutte le parti di questa transazione, inclusi gli input e gli output. In questo caso possiamo notare che la transazione che ha accreditato il nostro indirizzo con 50 millibit ha usato un input e ha generato due output. L input di questa transazione era l output di una transazione precedentemente confermata (mostrato come "vin txid" che inizia con d3c7). I due output corrispondono al valore di 50 millibit e ad un output contenente il resto reinviato al mittente. Possiamo esplorare ulteriormente la blockchain esaminando la transazione precedente referenziata dal suo txid in questa transazione usando lo stesso comando (i.e., gettransaction). Saltando da transazione a transazione possiamo seguire una catena di transazioni precedenti fino a che i bitcoin non siano stati trasmessi da un indirizzo di un proprietario a un altro. 17

56 Una volta che la transazione che abbiamo ricevuto è stata confermata e inclusa in un blocco il comando gettransaction ritornerà informazioni addizionali, mostrando l'identificatore dell hash di blocco nella quale l hash di transazione è stato incluso: Qui, possiamo vedere la nuova informazione nelle voci denominate blockhash (l hash del blocco in cui la transazione è stata inclusa), e blockindex con il valore 18 (indicando che la nostra transazione è stata la 18esima transazione nel determinato blocco). Indice del Database delle Transazioni e Opzione txindex Di base, Bitcoin Core, costruisce un database contenente solamente le transazioni relative al wallet dell utente. Se vuoi essere capace di accedere ad ogni transazione con comandi come gettransaction, avrai bisogno di configurare Bitcoin Core per costruire un indice delle transazioni completo, che può essere ottenuto attraverso l' opzione txindex. Imposta txindex=1 nel file di configurazione di Bitcoin Core (di solito trovato nella tua home directory in.bitcoin/bitcoin.conf). Una volta cambiato questo parametro, dovrai riavviare bitcoind e aspettare perchè ricostruisca l indice. Esplorando i Blocchi Comandi: getblock, getblockhash Ora che sappiamo in quale blocco la nostra transazione è stata inclusa, possiamo interrogare quel blocco. Utilizzeremo il comando getblock con l hash del blocco come parametro: Il blocco contiene 367 transazioni e come potete vedere, la 18esima transazione listata (9ca8f9...) è il txid di quella che ha accreditato 50 millibit al nostro indirizzo. La voce height ci dice che questo è il esimo blocco della blockchain. Possiamo inoltre recuperare un blocco tramite la sua block height usando il comando getblockhash, il quale richiede la block height come parametro e ritorna il block hash corrispondente per quel blocco: Qui, consultiamo il block hash del "genesis block", il primo blocco estratto da Satoshi Nakamoto, a quota zero. Consultare questo blocco mostra: I comandi getblock, getblockhash, e gettransaction possono essere usati per esplorare il databaseblockchain, programmaticamente. Creando, Firmando e Trasmettendo Transazioni Basate sul passaggio: [<phrase role="keep-together">unspent Output</phrase>] Comandi: listunspent, gettxout, createrawtransaction, decoderawtransaction, signrawtransaction, sendrawtransaction Bitcoin s transactions are based on the concept of spending "outputs," which are the result of previous 18

57 transactions, to create a transaction chain that transfers ownership from address to address. Our wallet has now received a transaction that assigned one such output to our address. Once this is confirmed, we can spend that output. All inizio, usiamo il comando listunspent per mostrare tutti gli output non spesi confermati presenti nel nostro wallet: $ bitcoin-cli listunspent Possiamo notare che la transazione 9ca8f9... creata con un output (con vout con indice 0) assegnata all indirizzo 1hvzSo... per l amount di 50 millibit, che a questo punto ha ricevuto sette conferme. Le transazioni utilizzano output creati precedentemente come loro input referenziandoli da indici precedenti txid e vout. Creeremo una transazione che spenderà lo 0esimo vout del txid 9ca8f9... come suo input e lo assegnerà a un nuovo output che invierà valore al nuovo indirizzo. Per iniziare, osserviamo l output con maggiore dettaglio. Usiamo il comando gettxout per ottenere i dettagli di questo unspent output. Gli output di transazione sono sempre referenziati da un txid e un vout, e questi sono i parametri che passiamo a gettxout: Quello che possiamo vedere qui è l output che ha assegnato 50 millibit al nostro indirizzo 1hvz... Per spendere questo output dobbiamo creare una nuova transazione. Per prima cosa, creiamo un indirizzo a cui invieremo il denaro: $ bitcoin-cli getnewaddress 1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb Invieremo 25 millibit al nuovo indirizzo 1LnfTn... che abbiamo appena creato nel nostro wallet. Nella nostra nuova transazione, spenderemo l output da 50 millibit e invieremo 25 millibit a questo nuovo indirizzo. Visto che dobbiamo spendere l output completamente dalla transazione precedente, dobbiamo anche generare del resto. Genereremo un resto indietro verso l indirizzo 1hvz..., inviando il resto indietro all indirizzo da cui originava il valore. Infine, dovremmo inoltre pagare una fee per questa transazione. Per pagare la fee, dovremmo ridurre l output del resto di 0.5 millibit, e ritornare 24.5 millibit in resto. La differenza tra la somma dei nuovi output (25 mbtc mbtc = 49.5 mbtc) e l input (50 mbtc) sarà riscosso come fee dai miner. Utilizzeremo il comando createrawtransaction per creare questa transazione. Come parametro di createrawtransaction forniremo l input di transazione (l unspent output di 50 millibit dalla nostra transazione confermata) e i due output di transazione (i bitcoin inviati al nuovo indirizzo e il resto che è stato re-inviato indietro all indirizzo precedente): Il comando createrawtransaction produce una stringa raw esadecimale che codifica i dettagli della transazione che abbiamo fornito. Confermiamo che tutto sia corretto decodificando questa stringa raw utilizzando il comando decoderawtransaction: 19

58 That looks correct! Our new transaction "consumes" the unspent output from our confirmed transaction and then spends it in two outputs, one for 25 millibits to our new address and one for 24.5 millibits as change back to the original address. The difference of 0.5 millibits represents the transaction fee and will be credited to the miner who finds the block that includes our transaction. As you might notice, the transaction contains an empty scriptsig because we haven t signed it yet. Without a signature, this transaction is meaningless; we haven t yet proven that we own the address from which the unspent output is sourced. By signing, we remove the lock on the output and prove that we own this output and can spend it. We use the signrawtransaction command to sign the transaction. It takes the raw transaction hex string as the parameter: TIP An encrypted wallet must be unlocked before a transaction is signed because signing requires access to the secret keys in the wallet. Il comando signrawtransaction ritorna un altra transazione raw con codifica esadecimale. La decodificheremo per vedere cosa è stato modificato, con il comando decoderawtransaction: A questo punto, gli input usati nella transazione contengono uno scriptsig, che è una firma digitale che prova la proprietà dell indirizzo 1hvz... e che rimuoverà il blocco (lock) sull output di modo che potrà essere speso. La firma rende questa transazione verificabile da ogni nodo nel network bitcoin. Adesso è tempo di inviare la nuova transazione appena creata al network. Possiamo fare questo con il comando sendrawtransaction, che prende la stringa raw esadecimale prodotta da signrawtransaction. Questa è la stessa stringa che abbiamo appena decodificato: Il comando sendrawtransaction ritorna un hash di transazione (transaction hash - txid) non appena invia la transazione al network. Possiamo a questo punto interrogare quell ID di transazione con gettransaction: 20

59 { } "amount" : , "fee" : , "confirmations" : 0, "txid" : "ae74538baa914f ba78429d5d84f36a e9f721dff584ac17b346", "time" : , "timereceived" : , "details" : [ { "account" : "", "address" : "1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb", "category" : "send", "amount" : , "fee" : }, { "account" : "", "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "category" : "send", "amount" : , "fee" : }, { "account" : "", "address" : "1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb", "category" : "receive", "amount" : }, { "account" : "", "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "category" : "receive", "amount" : } ] As before, we can also examine this in more detail using the getrawtransaction and decodetransaction commands. These commands will return the exact same hex string that we produced and decoded previously just before we sent it on the network. Client Alternativi, Librerie, e Toolkits Beyond the reference client (bitcoind), other clients and libraries can be used to interact with the bitcoin network and data structures. These are implemented in a variety of programming languages, 21

60 offering programmers native interfaces in their own language. Implementazioni alternativi includono: libbitcoin Development Toolkit Bitcoin C++ Cross-Platform bitcoin explorer Strumento Bitcoin da Riga di Comando bitcoin server Full Node Bitcoin e Query Server bitcoinj Una libreria client bitcoin full-node in Java btcd Una libreria client bitcoin full-node in Go Bits of Proof (BOP) Una implementazione di bitcoin enterprise-level picocoin Un implementazione in C di una libreria client leggera per bitcoin pybitcointools Una libreria bitcoin in Python pycoin Un altra libreria bitcoin in Python Esistono molte altre librerie scritte in una gran varietà di altri linguaggi di programmazione comuni e molte altre col tempo saranno create. Libbitcoin e Bitcoin Explorer The libbitcoin library is a cross-platform C++ development toolkit that supports the libbitcoin-server full node and the Bitcoin Explorer (bx) command line tool. The bx commands offer many of the same capabilities as the bitcoind client commands we illustrated in this chapter. The bx commands also offer some key management and manipulation tools that are not offered by bitcoind, including type-2 deterministic keys and mnemonic key encoding, as well as stealth address, payment, and query support. 22

61 Installare Bitcoin Explorer Per utilizzare Bitcoin Explorer, semplicemente scarica l eseguibile firmato per il tuo sistema operativo. Le build sono disponibili per mainnet e testnet, per Linux, OS X, e Windows. Digita bx senza alcun parametro per mostrare la lista di tutti i comandi disponibili (vedi [appdx_bx]). Bitcoin Explorer inoltre fornisce un installer per con la possibilità di compilare il progetto da sorgente su Linux e OS X, e anche un progetto Visual Studio per Windows. I sorgenti possono anche essere compilati manualmente usando Autotools. In questo modo verrà installata anche la libreria libbitcoin, che è una delle dipendenze. TIP Bitcoin Explorer offre molti altri comandi per codificare e decodificare indirizzi, e convertirli in e da differenti formati e rappresentazioni. Usali per esplorare i vari formati come Base16 (hex), Base58, Base58Check, Base64, etc. Installing Libbitcoin The libbitcoin library provides an installer for building from sources on Linux and OS X, as well as Visual Studio projects for Windows. Sources can also be built manually using Autotools. TIP L installer di Bitcoin Explorer installer installa sia bx che la libreria libbitcoin, quindi se hai già compilato bx da sorgente, puoi saltare questo passaggio. pycoin The Python library pycoin, originally written and maintained by Richard Kiss, is a Python-based library that supports manipulation of bitcoin keys and transactions, even supporting the scripting language enough to properly deal with nonstandard transactions. La libreria pycoin supporta sia Python 2 (2.7.x) e Python 3 (successivo alla 3.3); e viene fornito con utilità da riga di comando molto utili, ku e tx. Per installare pycoin 0.42 con Python 3 in un virtual environment (venv), usa il seguente comando: 23

62 $ python3 -m venv /tmp/pycoin $. /tmp/pycoin/bin/activate $ pip install pycoin==0.42 Scaricando/scompattando pycoin==0.42 Downloading pycoin-0.42.tar.gz (66kB): 66kB downloaded Lanciando setup.py (path:/tmp/pycoin/build/pycoin/setup.py) egg_info per il pacchetto pycoin Installing collected packages: pycoin Running setup.py install for pycoin Installing tx script to /tmp/pycoin/bin Installing cache_tx script to /tmp/pycoin/bin Installing bu script to /tmp/pycoin/bin Installing fetch_unspent script to /tmp/pycoin/bin Installing block script to /tmp/pycoin/bin Installing spend script to /tmp/pycoin/bin Installing ku script to /tmp/pycoin/bin Installing genwallet script to /tmp/pycoin/bin Successfully installed pycoin Cleaning up... $ Qui c è uno script Python di esempio per prendere e spendere un po di bitcoin usando la libreria pycoin: 24

63 #!/usr/bin/env python from pycoin.key import Key from pycoin.key.validate import is_address_valid, is_wif_valid from pycoin.services import spendables_for_address from pycoin.tx.tx_utils import create_signed_tx def get_address(which): while 1: print("enter the %s address=> " % which, end='') address = input() is_valid = is_address_valid(address) if is_valid: return address print("invalid address, please try again") src_address = get_address("source") spendables = spendables_for_address(src_address) print(spendables) while 1: print("enter the WIF for %s=> " % src_address, end='') wif = input() is_valid = is_wif_valid(wif) if is_valid: break print("invalid wif, please try again") key = Key.from_text(wif) if src_address not in (key.address(use_uncompressed=false), key.address(use_uncompressed=true)): print("** WIF doesn't correspond to %s" % src_address) print("the secret exponent is %d" % key.secret_exponent()) dst_address = get_address("destination") tx = create_signed_tx(spendables, payables=[dst_address], wifs=[wif]) print("here is the signed output transaction") print(tx.as_hex()) Per esempi che usano le utilità da riga-di-comando ku e tx, vedi [appdxbitcoinimpproposals]. 25

64 btcd btcd is a full-node bitcoin implementation written in Go. It currently downloads, validates, and serves the blockchain using the exact rules (including bugs) for block acceptance as the reference implementation, bitcoind. It also properly relays newly mined blocks, maintains a transaction pool, and relays individual transactions that have not yet made it into a block. It ensures that all individual transactions admitted to the pool follow the rules required and also includes the vast majority of the more strict checks that filter transactions based on miner requirements ("standard" transactions). One key difference between btcd and bitcoind is that btcd does not include wallet functionality, and this was a very intentional design decision. This means you can t actually make or receive payments directly with btcd. That functionality is provided by the btcwallet and btcgui projects, which are both under active development. Other notable differences between btcd and bitcoind include btcd support for both HTTP POST requests (such as bitcoind) and the preferred Websockets, and the fact that btcd s RPC connections are TLS-enabled by default. Installing btcd Per installare btcd per Windows, scarica e esegui il file msi disponibile in questo repository GitHub, o esegui il seguente comando su Linux, assumento che tu hai già installato il linguaggio Go: $ go get github.com/conformal/btcd/... Per aggiornare btcd all ultima versione, basta eseguire: $ go get -u -v github.com/conformal/btcd/... Controllare btcd btcd ha un certo numero di opzioni di configurazioni, che potrai vedere eseguendo: $ btcd --help btcd è fornito insieme a alcune utilità come btcctl, che è una utility da riga di comando che può essere usata sia per controllare che per interrogare btcd attraverso RPC. btcd non abilita il suo server RPC al normale avvio; devi configurare almeno un username e una password RPC nei seguenti file di configurazione: btcd.conf: 26

65 [Opzioni dell'applicazione] rpcuser=myuser rpcpass=somedecentp4ssw0rd btcctl.conf: [Opzioni dell'applicazione] rpcuser=myuser rpcpass=somedecentp4ssw0rd O se vuoi sovrascrivere i file di configurazione dalla riga di comando: $ btcd -u myuser -P SomeDecentp4ssw0rd $ btcctl -u myuser -P SomeDecentp4ssw0rd Per una lista di opzioni disponibili, esegui il seguente comando: $ btcctl --help 27

66 Chiavi, Indirizzi Wallet Introduzione La proprietà dei bitcoin si stabilisce attraverso chiavi digitali, indirizzi bitcoin, e firme digitali. Le chiavi digitali non sono in realtà memorizzate nella rete, ma sono invece create e memorizzate dagli utenti in un file, o in un semplice database, chiamato wallet (portafoglio). Le chiavi digitali nel wallet di un utente sono completamente indipendenti dal protocollo bitcoin e possono essere generate e gestite dal software del wallet dell utente software senza relazione con la blockchain o accesso a Internet. Le Chiavi consentono molte delle interessanti proprietà dei bitcoin, inclusa controllo e la fiducia (trust) de-centralizzata, attestazione della proprietà, e il modello di sicurezza a prova crittografica. Ogni transazione bitcoin richiede una firma valida per essere inclusa nella blockchain, che può essere generata solo con chiavi digitali valide; pertanto, chiunque ha una copia di quelle chiavi ha il controllo del bitcoin in quel conto. Si tratta di coppie di chiavi composte da una chiave privata (segreta) e una chiave pubblica. Pensate alla chiave pubblica come ad un numero di conto bancario e la chiave privata come il PIN segreto, o la firma su un assegno che consente di controllare il conto. Queste chiavi digitali molto raramente vengono viste dagli utenti bitcoin. Per lo più, sono memorizzate all interno del file del wallet e gestite dal software del wallet bitcoin. Nella parte di pagamento di una transazione bitcoin, la chiave pubblica del destinatario è rappresentata dalla sua impronta digitale, chiamata indirizzo bitcoin, che viene utilizzata allo stesso modo del nome del beneficiario su un assegno (cioè, "Pagare all ordine di"). Nella maggior parte dei casi, un indirizzo bitcoin è generato da e corrisponde ad una chiave pubblica. Tuttavia, non tutti gli indirizzi bitcoin rappresentano chiavi pubbliche; possono anche rappresentare altri beneficiari come gli script, come vedremo più avanti in questo capitolo. In questo modo, gli indirizzi bitcoin astraggono il destinatario dei fondi, rendendo flessibile le destinazioni delle transazione, simile ad assegni di carta: un unico strumento di pagamento che può essere utilizzato per pagare nei conti delle persone, pagare nei conti delle società, pagare le bollette, o pagare in contanti. L indirizzo Bitcoin è l unica rappresentazione delle chiavi che gli utenti regolarmente vedono, perché questa è la parte di cui hanno bisogno di condividere con il mondo. In questo capitolo introdurremo i wallet (portafogli), che contengono chiavi crittografiche. Vedremo come le chiavi vengono generate, archiviate, e gestite. Esamineremo i vari formati di codifica utilizzati per rappresentare le chiavi pubbliche e private, gli indirizzi e gli indirizzi script (script address). Infine, prenderemo in considerazione usi speciali di chiavi: per firmare i messaggi, per dimostrare la proprietà, e per creare vanity address e paper wallet (wallet su carta). La Crittografia a Chiave Pubblica e le Criptovalute La crittografia a chiave pubblica è stata inventata negli anni '70 (1970) ed è una delle basi matematiche dei computer e della sicurezza informatica. Da quando stata inventata la crittografia a chiave pubblica, sono state scoperte diverse funzioni 1

67 matematiche idonee, come ad esempio l elevazione a potenza dei numeri primi e la moltiplicazione a curva ellittica. Queste funzioni matematiche sono praticamente irreversibili, nel senso che sono facili da calcolare in una direzione e impossibili da calcolare nella direzione opposta. Sulla base di queste funzioni matematiche, la crittografia consente la creazione di segreti digitali e firme digitali non falsificabili. Bitcoin usa la moltiplicazione a curva ellittica come base per la sua crittografia a chiave pubblica. In bitcoin, usiamo la crittografia a chiave pubblica per creare una coppia di chiavi che controlla l accesso ai bitcoin. La coppia di chiavi consiste di una chiave privata e derivata da essa un unica chiave pubblica. La chiave pubblica è usata per ricevere bitcoin, e la chiave privata è usata per autorizzare transazioni per spenderli. C è una relazione matematica tra la chiave pubblica e quella privata che permette alla chiave privata di essere usata per generare firme sui messaggi. Questa firma può essere validata attraverso la chiave pubblica senza rivelare la chiave privata. Quando si spendono bitcoin, il proprietario attuale dei bitcoin presenta la sua chiave pubblica e una firma (differente ogni volta, ma creata dalla stessa chiave privata) in una transazione per autorizzare il rilascio di quei bitcoin. TIP Nella maggior parte delle implementazioni di wallet, le chiavi privata e pubblica sono salvate insieme come coppia di chiavi per convenienza. Comunque, la chiave pubblica può essere ricavata dalla chiave privata, quindi è possibile salvare anche solo la chiave privata. Chiavi, Privata e Pubblica A bitcoin wallet contains a collection of key pairs, each consisting of a private key and a public key. The private key (k) is a number, usually picked at random. From the private key, we use elliptic curve multiplication, a one-way cryptographic function, to generate a public key (K). From the public key (K), we use a one-way cryptographic hash function to generate a bitcoin address (A). In this section, we will start with generating the private key, look at the elliptic curve math that is used to turn that into a public key, and finally, generate a bitcoin address from the public key. The relationship between private key, public key, and bitcoin address is shown in Chiave privata, chiave pubblica e indirizzo bitcoin. Figure 1. Chiave privata, chiave pubblica e indirizzo bitcoin 2

68 Chiavi Private A private key is simply a number, picked at random. Ownership and control over the private key is the root of user control over all funds associated with the corresponding bitcoin address. The private key is used to create signatures that are required to spend bitcoins by proving ownership of funds used in a transaction. The private key must remain secret at all times, because revealing it to third parties is equivalent to giving them control over the bitcoins secured by that key. The private key must also be backed up and protected from accidental loss, because if it s lost it cannot be recovered and the funds secured by it are forever lost, too. TIP La chiave privata bitcoin è soltanto un numero. Puoi generare le tue chiavi private in modo casuale utilizzando semplicemente una moneta, una matita e un foglio di carta: lancia una moneta 256 volte e otterrai le cifre binarie di una chiave privata casuale che puoi utilizzare in un wallet bitcoin. La chiave pubblica può essere successivamente generata da quella privata. Generando una chiave privata da un numero casuale Il primo e il più importante passo per generare chiavi per trovare una fonte sicura di entropia, o casualità. Creare una chiave bitcoin é essenzialmente la stessa cosa di "Scegli un numero tra 1 e " Il metodo esatto usato per scegliere quel numero non é importante fintanto che non è prevedibile o ripetibile. Il software bitcoin usa il generatore di numeri casuali del sistema operativo per produrre 256 bit di entropia (casualità). Di solito, il generatore di numeri casuali dell OS è inizializzato da una fonte umana di casualità, che è il motivo per il quale qualche programma potrebbe chiederti di muovere il mouse a caso per qualche secondo. Per i veri paranoici, niente batte i dadi, una matita e un pezzo di carta. Più accuratamente, la chiave privata potrebbe essere un qualsiasi numero da 1 e n - 1, dove n è una costante (n = * 10 77, un po meno di ) definita come l ordine della curva ellittica usata in bitcoin (vedi Crittografia a Curve Ellittiche). Per creare una chiave del genere, sceglieremo casualmente un numero da 256-bit e controlleremo che sia inferiore di n - 1. Nei termini da programmatori, questo viene realizzato tramite il dare in pasto una stringa più lunga di bit casuali, all algoritmo di hash SHA256 che produrrà convenientemente un numero da 256-bit. Se il risultato è meno di n - 1, avremo una chiave privata adeguata. Altrimenti, riproveremo nuovamente con un altro numero casuale. TIP Do not write your own code to create a random number or use a "simple" random number generator offered by your programming language. Use a cryptographically secure pseudo-random number generator (CSPRNG) with a seed from a source of sufficient entropy. Study the documentation of the random number generator library you choose to make sure it is cryptographically secure. Correct implementation of the CSPRNG is critical to the security of the keys. La seguente è una chiave privata randomicamente (k) mostrata nella sua rappresentazione esadecimale (256 cifre mostrate come 64 cifre esadecimali, ognuna da 4 bit): 3

69 1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD TIP La dimensione dello spazio di una chiave privata bitcoion, è un numero incomprensibilmente grande. E' approssimativamente in cifre decimali. E' stato stimato che l universo visibile contenga atomi. To generate a new key with the Bitcoin Core client (see [ch03_bitcoin_client]), use the getnewaddress command. For security reasons it displays the public key only, not the private key. To ask bitcoind to expose the private key, use the dumpprivkey command. The dumpprivkey command shows the private key in a Base58 checksum-encoded format called the Wallet Import Format (WIF), which we will examine in more detail in Formati delle Chiavi Private. Here s an example of generating and displaying a private key using these two commands: $ bitcoind getnewaddress 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy $ bitcoind dumpprivkey 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ Il comando dumpprivkey apre il wallet e estrae la chiave privata che è stata generata dal comando getnewaddress. Non è invece possibile per bitcoind conoscere la chiave privata avendo solo la chiave pubblica, a meno che non siano entrambe salvate nel wallet. TIP Il comando dumpprivkey non genera una chiave privata da una chiave pubblica, visto che è impossibile. Il comando semplicemente rivela la chiave privata che è già conosciuta al wallet e che è stata generata dal comando getnewaddress. You can also use the Bitcoin Explorer command-line tool (see [libbitcoin]) to generate and display private keys with the commands seed, ec-new and ec-to-wif: $ bx seed bx ec-new bx ec-to-wif 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn Chiavi Pubbliche The public key is calculated from the private key using elliptic curve multiplication, which is irreversible: \(K = k * G\) where k is the private key, G is a constant point called the generator point and K is the resulting public key. The reverse operation, known as "finding the discrete logarithm" calculating k if you know K is as difficult as trying all possible values of k, i.e., a bruteforce search. Before we demonstrate how to generate a public key from a private key, let s look at elliptic curve cryptography in a bit more detail. 4

70 Crittografia a Curve Ellittiche Elliptic curve cryptography is a type of asymmetric or public-key cryptography based on the discrete logarithm problem as expressed by addition and multiplication on the points of an elliptic curve. Una curva ellittica è un esempio di curva ellittica, simile a quella usata da bitcoin. Figure 2. Una curva ellittica Bitcoin uses a specific elliptic curve and set of mathematical constants, as defined in a standard called secp256k1, established by the National Institute of Standards and Technology (NIST). The secp256k1 curve is defined by the following function, which produces an elliptic curve: 5

71 o Il mod p (modulo del numero primo p) indica che questa curva è su un campo finito di numeri primi di ordine p, che possiamo scrivere come \(\mathbb{f}_p\), dove p = , un numero primo molto grande. Because this curve is defined over a finite field of prime order instead of over the real numbers, it looks like a pattern of dots scattered in two dimensions, which makes it difficult to visualize. However, the math is identical as that of an elliptic curve over the real numbers. As an example, Crittografia a curve ellittiche: visualizzando una curva ellittica su F(p), con p=17 shows the same elliptic curve over a much smaller finite field of prime order 17, showing a pattern of dots on a grid. The secp256k1 bitcoin elliptic curve can be thought of as a much more complex pattern of dots on a unfathomably large grid. Figure 3. Crittografia a curve ellittiche: visualizzando una curva ellittica su F(p), con p=17 Quindi, per esempio, il seguente è un punto P con coordinate (x,y) che è un punto sulla curva secp256k1. Puoi controllarlo tu stesso usando Python: 6

72 P = ( , ) Python (default, Mar , 19:23:13) [GCC Compatible Apple LLVM 5.1 (clang )] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> p = >>> x = >>> y = >>> (x ** y**2) % p 0 In elliptic curve math, there is a point called the "point at infinity," which roughly corresponds to the role of 0 in addition. On computers, it s sometimes represented by x = y = 0 (which doesn t satisfy the elliptic curve equation, but it s an easy separate case that can be checked). There is also a + operator, called "addition," which has some properties similar to the traditional addition of real numbers that grade school children learn. Given two points P 1 and P 2 on the elliptic curve, there is a third point P 3 = P 1 + P 2, also on the elliptic curve. Geometrically, this third point P 3 is calculated by drawing a line between P 1 and P 2. This line will intersect the elliptic curve in exactly one additional place. Call this point P 3 ' = (x, y). Then reflect in the x-axis to get P 3 = (x, y). Ci sono un paio di casi particolari che chiariscono il bisogno di "puntare all infinito". If P 1 and P 2 are the same point, the line "between" P 1 and P 2 should extend to be the tangent on the curve at this point P 1. This tangent will intersect the curve in exactly one new point. You can use techniques from calculus to determine the slope of the tangent line. These techniques curiously work, even though we are restricting our interest to points on the curve with two integer coordinates! In some cases (i.e., if P 1 and P 2 have the same x values but different y values), the tangent line will be exactly vertical, in which case P3 = "point at infinity." If P 1 is the "point at infinity," then the sum P 1 + P 2 = P 2. Similary, if P 2 is the point at infinity, then P 1 + P 2 = P 1. This shows how the point at infinity plays the role of 0. It turns out that + is associative, which means that (A + B) + C = A + (B + C). That means we can write A + B + C without parentheses without any ambiguity. Now that we have defined addition, we can define multiplication in the standard way that extends addition. For a point P on the elliptic curve, if k is a whole number, then kp = P + P + P + + P (k times). 7

73 Note that k is sometimes confusingly called an "exponent" in this case. Generare una Chiave Pubblica Starting with a private key in the form of a randomly generated number k, we multiply it by a predetermined point on the curve called the generator point G to produce another point somewhere else on the curve, which is the corresponding public key K. The generator point is specified as part of the secp256k1 standard and is always the same for all keys in bitcoin: where k is the private key, G is the generator point, and K is the resulting public key, a point on the curve. Because the generator point is always the same for all bitcoin users, a private key k multiplied with G will always result in the same public key K. The relationship between k and K is fixed, but can only be calculated in one direction, from k to K. That s why a bitcoin address (derived from K) can be shared with anyone and does not reveal the user s private key (k). TIP Una chiave privata può essere convertita in una chiave pubblica, ma una chiave pubblica non può essere ri-convertita in una chiave privata perchè la funzione matematica utilizzata è unidirezionale. Implementando la moltiplicazione complessa (teoria delle curve ellittiche), prendiamo la chiave privata k generata precedentemente e la moltiplichiamo con il punto generatore G per trovare la chiave pubblica K: K = 1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD * G La Chiave Pubblica K è definita come punto K = (x,y): K = (x, y) dove, x = F028892BAD7ED57D2FB57BF33081D5CFCF6F9ED3D3D7F159C2E2FFF579DC341A y = 07CF33DA18BD734C600B96A72BBC4749D5141C90EC8AC328AE52DDFE2E505BDB To visualize multiplication of a point with an integer, we will use the simpler elliptic curve over the real numbers remember, the math is the same. Our goal is to find the multiple kg of the generator point G. That is the same as adding G to itself, k times in a row. In elliptic curves, adding a point to itself is the equivalent of drawing a tangent line on the point and finding where it intersects the curve again, then reflecting that point on the x-axis. Crittografia Ellittica: Visualizzando la moltiplicazione di un punto G per un intero k su una curva ellittica mostra il processo di derivazione di G, 2G, 4G, come un operazione geometrica sulla curva. 8

74 TIP Most bitcoin implementations use the OpenSSL cryptographic library to do the elliptic curve math. For example, to derive the public key, the function EC_POINT_mul() is used. Figure 4. Crittografia Ellittica: Visualizzando la moltiplicazione di un punto G per un intero k su una curva ellittica Indirizzi Bitcoin A bitcoin address is a string of digits and characters that can be shared with anyone who wants to send you money. Addresses produced from public keys consist of a string of numbers and letters, beginning with the digit "1". Here s an example of a bitcoin address: 9

75 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy The bitcoin address is what appears most commonly in a transaction as the "recipient" of the funds. If we were to compare a bitcoin transaction to a paper check, the bitcoin address is the beneficiary, which is what we write on the line after "Pay to the order of." On a paper check, that beneficiary can sometimes be the name of a bank account holder, but can also include corporations, institutions, or even cash. Because paper checks do not need to specify an account, but rather use an abstract name as the recipient of funds, that makes paper checks very flexible as payment instruments. Bitcoin transactions use a similar abstraction, the bitcoin address, to make them very flexible. A bitcoin address can represent the owner of a private/public key pair, or it can represent something else, such as a payment script, as we will see in [p2sh]. For now, let s examine the simple case, a bitcoin address that represents, and is derived from, a public key. The bitcoin address is derived from the public key through the use of one-way cryptographic hashing. A "hashing algorithm" or simply "hash algorithm" is a one-way function that produces a fingerprint or "hash" of an arbitrary-sized input. Cryptographic hash functions are used extensively in bitcoin: in bitcoin addresses, in script addresses, and in the mining proof-of-work algorithm. The algorithms used to make a bitcoin address from a public key are the Secure Hash Algorithm (SHA) and the RACE Integrity Primitives Evaluation Message Digest (RIPEMD), specifically SHA256 and RIPEMD160. Iniziando con la chiave pubblica K, calcoliamo l hash SHA256 e poi calcoliamo l hash RIPEMD160 del risultato, producendo un numero a 160-bit (20-byte): where K is the public key and A is the resulting bitcoin address. TIP A bitcoin address is not the same as a public key. Bitcoin addresses are derived from a public key using a one-way function. Bitcoin addresses are almost always presented to users in an encoding called "Base58Check" (see Encoding Base58 e Base58Check), which uses 58 characters (a Base58 number system) and a checksum to help human readability, avoid ambiguity, and protect against errors in address transcription and entry. Base58Check is also used in many other ways in bitcoin, whenever there is a need for a user to read and correctly transcribe a number, such as a bitcoin address, a private key, an encrypted key, or a script hash. In the next section we will examine the mechanics of Base58Check encoding and decoding, and the resulting representations. Public key to bitcoin address: conversion of a public key into a bitcoin address illustrates the conversion of a public key into a bitcoin address. 10

76 Figure 5. Public key to bitcoin address: conversion of a public key into a bitcoin address Encoding Base58 e Base58Check In order to represent long numbers in a compact way, using fewer symbols, many computer systems use mixed-alphanumeric representations with a base (or radix) higher than 10. For example, whereas 11

77 the traditional decimal system uses the 10 numerals 0 through 9, the hexadecimal system uses 16, with the letters A through F as the six additional symbols. A number represented in hexadecimal format is shorter than the equivalent decimal representation. Even more compact, Base-64 representation uses 26 lower-case letters, 26 capital letters, 10 numerals, and two more characters such as "+" and "/" to transmit binary data over text-based media such as . Base-64 is most commonly used to add binary attachments to . Base58 is a text-based binary-encoding format developed for use in bitcoin and used in many other cryptocurrencies. It offers a balance between compact representation, readability, and error detection and prevention. Base58 is a subset of Base64, using the upper- and lowercase letters and numbers, but omitting some characters that are frequently mistaken for one another and can appear identical when displayed in certain fonts. Specifically, Base58 is Base64 without the 0 (number zero), O (capital o), l (lower L), I (capital i), and the symbols "\+" and "/". Or, more simply, it is a set of lower and capital letters and numbers without the four (0, O, l, I) just mentioned. Example 1. bitcoin s Base58 alphabet ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz To add extra security against typos or transcription errors, Base58Check is a Base58 encoding format, frequently used in bitcoin, which has a built-in error-checking code. The checksum is an additional four bytes added to the end of the data that is being encoded. The checksum is derived from the hash of the encoded data and can therefore be used to detect and prevent transcription and typing errors. When presented with a Base58Check code, the decoding software will calculate the checksum of the data and compare it to the checksum included in the code. If the two do not match, that indicates that an error has been introduced and the Base58Check data is invalid. For example, this prevents a mistyped bitcoin address from being accepted by the wallet software as a valid destination, an error that would otherwise result in loss of funds. To convert data (a number) into a Base58Check format, we first add a prefix to the data, called the "version byte," which serves to easily identify the type of data that is encoded. For example, in the case of a bitcoin address the prefix is zero (0x00 in hex), whereas the prefix used when encoding a private key is 128 (0x80 in hex). A list of common version prefixes is shown in Prefisso di versione Base58Check e esempi del risultato. Next, we compute the "double-sha" checksum, meaning we apply the SHA256 hash-algorithm twice on the previous result (prefix and data): checksum = SHA256(SHA256(prefix+data)) From the resulting 32-byte hash (hash-of-a-hash), we take only the first four bytes. These four bytes serve as the error-checking code, or checksum. The checksum is concatenated (appended) to the end. The result is composed of three items: a prefix, the data, and a checksum. This result is encoded using 12

78 the Base58 alphabet described previously. Base58Check encoding: a Base58, versioned, and checksummed format for unambiguously encoding bitcoin data illustrates the Base58Check encoding process. Figure 6. Base58Check encoding: a Base58, versioned, and checksummed format for unambiguously encoding bitcoin data In bitcoin, most of the data presented to the user is Base58Check-encoded to make it compact, easy to read, and easy to detect errors. The version prefix in Base58Check encoding is used to create easily distinguishable formats, which when encoded in Base58 contain specific characters at the beginning of the Base58Check-encoded payload. These characters make it easy for humans to identify the type of data that is encoded and how to use it. This is what differentiates, for example, a Base58Check-encoded bitcoin address that starts with a 1 from a Base58Check-encoded private key WIF format that starts with a 5. Some example version prefixes and the resulting Base58 characters are shown in Prefisso di versione Base58Check e esempi del risultato. Table 1. Prefisso di versione Base58Check e esempi del risultato 13

79 Tipo Prefisso di versione (esadecimale) Prefisso del risultato Base58 Indirizzo Bitcoin 0x00 1 Indirizzo Pay-to-Script-Hash 0x05 3 Indirizzo Bitcoin Testnet 0x6F m o n Private Key WIF 0x80 5, K or L Chiave Privata Criptata BIP38 0x0142 6P Chiave Pubblica Estesa BIP32 0x0488B21E xpub Let s look at the complete process of creating a bitcoin address, from a private key, to a public key (a point on the elliptic curve), to a double-hashed address and finally, the Base58Check encoding. The C++ code in Creazione di un indirizzo bitcoin Base58Check-encoded da una chiave privata shows the complete step-by-step process, from private key to Base58Check-encoded bitcoin address. The code example uses the libbitcoin library introduced in [alt_libraries] for some helper functions. 14

80 Example 2. Creazione di un indirizzo bitcoin Base58Check-encoded da una chiave privata #include <bitcoin/bitcoin.hpp> int main() { // Private secret key. bc::ec_secret secret; bool success = bc::decode_base16(secret, " a5807b2eccc082c8c3fbb988a973cacf1a7df9ce725c31b14776"); assert(success); // Get public key. bc::ec_point public_key = bc::secret_to_public_key(secret); std::cout << "Public key: " << bc::encode_hex(public_key) << std::endl; // Create Bitcoin address. // Normally you can use: // bc::payment_address payaddr; // bc::set_public_key(payaddr, public_key); // const std::string address = payaddr.encoded(); // Compute hash of public key for P2PKH address. const bc::short_hash hash = bc::bitcoin_short_hash(public_key); bc::data_chunk unencoded_address; // Reserve 25 bytes // [ version:1 ] // [ hash:20 ] // [ checksum:4 ] unencoded_address.reserve(25); // Version byte, 0 is normal BTC address (P2PKH). unencoded_address.push_back(0); // Hash data bc::extend_data(unencoded_address, hash); // Checksum is computed by hashing data, and adding 4 bytes from hash. bc::append_checksum(unencoded_address); // Finally we must encode the result in Bitcoin's base58 encoding assert(unencoded_address.size() == 25); const std::string address = bc::encode_base58(unencoded_address); } std::cout << "Address: " << address << std::endl; return 0; The code uses a predefined private key so that it produces the same bitcoin address every time it is 15

81 run, as shown in Compilando ed eseguendo il codice addr. Example 3. Compilando ed eseguendo il codice addr # Compila il codice addr.cpp $ g++ -o addr addr.cpp $(pkg-config --cflags --libs libbitcoin) # Esegui l'eseguibile addr Run the addr executable $./addr Public key: 0202a f2abbdc68da3df929f938c3399dd79fac1b51b0e4ad1d26a47aa Address: 1PRTTaJesdNovgne6Ehcdu1fpEdX7913CK Formati di Chiavi Both private and public keys can be represented in a number of different formats. These representations all encode the same number, even though they look different. These formats are primarily used to make it easy for people to read and transcribe keys without introducing errors. Formati delle Chiavi Private The private key can be represented in a number of different formats, all of which correspond to the same 256-bit number. Rappresentazioni di chiavi private (formati di codifica) shows three common formats used to represent private keys. Table 2. Rappresentazioni di chiavi private (formati di codifica) Tipo Prefisso Descrizione Hex Nessuno 64 cifre esadecimali WIF 5 encoding Base58Check: Base58 con prefisso di versione di 128 e checksum a 32-bit WIF-compressed K or L Come sopra, con l aggiunta di un suffisso 0x01 precedente all encoding Esempio: Stessa chiave, formati differenti mostra la chiave provata generata nei seguenti tre formati. Table 3. Esempio: Stessa chiave, formati differenti Formato Hex WIF Chiave Privata 1e99423a4ed27608a15a2616a2b0e9e52ced330ac53 0edcc32c8ffc6a526aedd 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2Jpbnk eyhfsyb1jcn 16

82 Formato WIF-compressed Chiave Privata KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf 6YwgdGWZgawvrtJ Tutte queste rappresentazioni sono modi diversi di mostrare lo stesso numero, la stessa chiave privata. Sembrano diverse, ma qualunque di questi formati possono essere convertiti in qualsiasi altro formato. Usiamo il comando wif-to-ec dal Bitcoin Explorer (vedi [libbitcoin]) per mostrare entrambe le chiavi WIF rappresentanti la stessa chiave privata: $ bx wif-to-ec 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd $ bx wif-to-ec KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd Decodifica da Base58Check The Bitcoin Explorer commands (see [libbitcoin]) make it easy to write shell scripts and command-line "pipes" that manipulate bitcoin keys, addresses, and transactions. You can use Bitcoin Explorer to decode the Base58Check format on the command line. We use the base58check-decode command to decode the uncompressed key: $ bx base58check-decode 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn wrapper { checksum payload 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd version 128 } The result contains the key as payload, the Wallet Import Format (WIF) version prefix 128, and a checksum. Notice that the "payload" of the compressed key is appended with the suffix 01, signalling that the derived public key is to be compressed. 17

83 $ bx base58check-decode KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ wrapper { checksum payload 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd01 version 128 } Codifica da esadecimale a Base58Check To encode into Base58Check (the opposite of the previous command), we use the base58check-encode command from Bitcoin Explorer (see [libbitcoin]) and provide the hex private key, followed by the Wallet Import Format (WIF) version prefix 128: bx base58check-encode 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd --version 128 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn Codifica da hex (chiave compressa) a Base58Check Per effettuare la codifica in Base58Check come chiave privata "compressa" (vedi Chiavi private compresse), accodiamo il suffisso 01 alla chiave esadecimale e poi la codifichiamo come abbiamo fatto prima: $ bx base58check-encode 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd01 --version 128 KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ Il formato WIF-compressed risultante inizia con una "K". Questo denota che la chiave privata contenuta ha il suffisso di "01" e sarà usata per produrre solo chiavi pubbliche compresse (vedi Chiavi pubbliche compresse). Formati di Chiavi Pubbliche Public keys are also presented in different ways, most importantly as either compressed or uncompressed public keys. As we saw previously, the public key is a point on the elliptic curve consisting of a pair of coordinates (x,y). It is usually presented with the prefix 04 followed by two 256-bit numbers, one for the x coordinate of the point, the other for the y coordinate. The prefix 04 is used to distinguish uncompressed public keys from compressed public keys that begin with a 02 or a 03. Here s the public key generated by the private key we created earlier, shown as the coordinates x and y: 18

84 x = F028892BAD7ED57D2FB57BF33081D5CFCF6F9ED3D3D7F159C2E2FFF579DC341A y = 07CF33DA18BD734C600B96A72BBC4749D5141C90EC8AC328AE52DDFE2E505BDB Here s the same public key shown as a 520-bit number (130 hex digits) with the prefix 04 followed by x and then y coordinates, as 04 x y: K = 04F028892BAD7ED57D2FB57BF33081D5CFCF6F9ED3D3D7F159C2E2FFF579DC341A<?pdfcr?>07CF33DA18BD734C600B96A72BBC4749D5141C90EC8AC328AE52DDFE2E505BDB Chiavi pubbliche compresse <?dbhtml orphans="4"?>compressed public keys were introduced to bitcoin to reduce the size of transactions and conserve disk space on nodes that store the bitcoin blockchain database. Most transactions include the public key, required to validate the owner s credentials and spend the bitcoin. Each public key requires 520 bits (prefix \+ x \+ y), which when multiplied by several hundred transactions per block, or tens of thousands of transactions per day, adds a significant amount of data to the blockchain. As we saw in the section Chiavi Pubbliche, a public key is a point (x,y) on an elliptic curve. Because the curve expresses a mathematical function, a point on the curve represents a solution to the equation and, therefore, if we know the x coordinate we can calculate the y coordinate by solving the equation y 2 mod p = (x 3 + 7) mod p. That allows us to store only the x coordinate of the public key point, omitting the y coordinate and reducing the size of the key and the space required to store it by 256 bits. An almost 50% reduction in size in every transaction adds up to a lot of data saved over time! Whereas uncompressed public keys have a prefix of 04, compressed public keys start with either a 02 or a 03 prefix. Let s look at why there are two possible prefixes: because the left side of the equation is y 2, that means the solution for y is a square root, which can have a positive or negative value. Visually, this means that the resulting y coordinate can be above the x-axis or below the x-axis. As you can see from the graph of the elliptic curve in Una curva ellittica, the curve is symmetric, meaning it is reflected like a mirror by the x-axis. So, while we can omit the y coordinate we have to store the sign of y (positive or negative), or in other words, we have to remember if it was above or below the x-axis because each of those options represents a different point and a different public key. When calculating the elliptic curve in binary arithmetic on the finite field of prime order p, the y coordinate is either even or odd, which corresponds to the positive/negative sign as explained earlier. Therefore, to distinguish between the two possible values of y, we store a compressed public key with the prefix 02 if the y is even, and 03 if it is odd, allowing the software to correctly deduce the y coordinate from the x coordinate and uncompress the public key to the full coordinates of the point. Public key compression is illustrated in Compressione di una chiave pubblicapublic key compression. 19

85 Figure 7. Compressione di una chiave pubblicapublic key compression Here s the same public key generated previously, shown as a compressed public key stored in 264 bits (66 hex digits) with the prefix 03 indicating the y coordinate is odd: 20

86 K = 03F028892BAD7ED57D2FB57BF33081D5CFCF6F9ED3D3D7F159C2E2FFF579DC341A This compressed public key corresponds to the same private key, meaning that it is generated from the same private key. However, it looks different from the uncompressed public key. More importantly, if we convert this compressed public key to a bitcoin address using the double-hash function (RIPEMD160(SHA256(K))) it will produce a different bitcoin address. This can be confusing, because it means that a single private key can produce a public key expressed in two different formats (compressed and uncompressed) that produce two different bitcoin addresses. However, the private key is identical for both bitcoin addresses. Compressed public keys are gradually becoming the default across bitcoin clients, which is having a significant impact on reducing the size of transactions and therefore the blockchain. However, not all clients support compressed public keys yet. Newer clients that support compressed public keys have to account for transactions from older clients that do not support compressed public keys. This is especially important when a wallet application is importing private keys from another bitcoin wallet application, because the new wallet needs to scan the blockchain to find transactions corresponding to these imported keys. Which bitcoin addresses should the bitcoin wallet scan for? The bitcoin addresses produced by uncompressed public keys, or the bitcoin addresses produced by compressed public keys? Both are valid bitcoin addresses, and can be signed for by the private key, but they are different addresses! To resolve this issue, when private keys are exported from a wallet, the Wallet Import Format that is used to represent them is implemented differently in newer bitcoin wallets, to indicate that these private keys have been used to produce compressed public keys and therefore compressed bitcoin addresses. This allows the importing wallet to distinguish between private keys originating from older or newer wallets and search the blockchain for transactions with bitcoin addresses corresponding to the uncompressed, or the compressed, public keys, respectively. Let s look at how this works in more detail, in the next section. Chiavi private compresse Ironically, the term "compressed private key" is misleading, because when a private key is exported as WIF-compressed it is actually one byte longer than an "uncompressed" private key. That is because it has the added 01 suffix, which signifies it comes from a newer wallet and should only be used to produce compressed public keys. Private keys are not compressed and cannot be compressed. The term "compressed private key" really means "private key from which compressed public keys should be derived," whereas "uncompressed private key" really means "private key from which uncompressed public keys should be derived." You should only refer to the export format as "WIFcompressed" or "WIF" and not refer to the private key as "compressed" to avoid further confusion. Remember, these formats are not used interchangeably. In a newer wallet that implements compressed public keys, the private keys will only ever be exported as WIF-compressed (with a K or L prefix). If the wallet is an older implementation and does not use compressed public keys, the private keys will only ever be exported as WIF (with a 5 prefix). The goal here is to signal to the wallet 21

87 importing these private keys whether it must search the blockchain for compressed or uncompressed public keys and addresses. If a bitcoin wallet is able to implement compressed public keys, it will use those in all transactions. The private keys in the wallet will be used to derive the public key points on the curve, which will be compressed. The compressed public keys will be used to produce bitcoin addresses and those will be used in transactions. When exporting private keys from a new wallet that implements compressed public keys, the Wallet Import Format is modified, with the addition of a one-byte suffix 01 to the private key. The resulting Base58Check-encoded private key is called a "Compressed WIF" and starts with the letter K or L, instead of starting with "5" as is the case with WIF-encoded (non-compressed) keys from older wallets. Esempio: Stessa chiave, formati differenti shows the same key, encoded in WIF and WIF-compressed formats. Table 4. Esempio: Stessa chiave, formati differenti Formato Esadecimale WIF Esadecimale-compressa WIF-compressed Chiave Privata 1E99423A4ED27608A15A2616A2B0E9E52CED330A C530EDCC32C8FFC6A526AEDD 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2Jpbnk eyhfsyb1jcn 1E99423A4ED27608A15A2616A2B0E9E52CED330A C530EDCC32C8FFC6A526AEDD_01_ KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf 6YwgdGWZgawvrtJ TIP "Compressed private keys" is a misnomer! They are not compressed; rather, the WIFcompressed format signifies that they should only be used to derive compressed public keys and their corresponding bitcoin addresses. Ironically, a "WIF-compressed" encoded private key is one byte longer because it has the added 01 suffix to distinguish it from an "uncompressed" one. Implementando le Chiavi e gli Indirizzi in Python The most comprehensive bitcoin library in Python is pybitcointools by Vitalik Buterin. In Generazione di chiavi e indirizzi e formattazione tramite la libreria pybitcointools, we use the pybitcointools library (imported as "bitcoin") to generate and display keys and addresses in various formats. Example 4. Generazione di chiavi e indirizzi e formattazione tramite la libreria pybitcointools import bitcoin 22

88 # Generate a random private key valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.n print "Private Key (hex) is: ", private_key print "Private Key (decimal) is: ", decoded_private_key # Convert private key to WIF format wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print "Private Key (WIF) is: ", wif_encoded_private_key # Add suffix "01" to indicate a compressed private key compressed_private_key = private_key + '01' print "Private Key Compressed (hex) is: ", compressed_private_key # Generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print "Private Key (WIF-Compressed) is: ", wif_compressed_private_key # Multiply the EC generator point G with the private key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.g, decoded_private_key) print "Public Key (x,y) coordinates is:", public_key # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key,'hex') print "Public Key (hex) is:", hex_encoded_public_key # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) print "Compressed Public Key (hex) is:", hex_compressed_public_key # Generate bitcoin address from public key print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(public_key) # Generate compressed bitcoin address from compressed public key print "Compressed Bitcoin Address (b58check) is:", \ bitcoin.pubkey_to_address(hex_compressed_public_key) 23

89 Eseguendo key-to-address-ecc-example.py mostra l output ottenuto eseguendo questo codice. Example 5. Eseguendo key-to-address-ecc-example.py Uno script che dimostra la matematica a curve ellittiche usata per le chiavi bitcoin is another example, using the Python ECDSA library for the elliptic curve math and without using any specialized bitcoin libraries. Example 6. Uno script che dimostra la matematica a curve ellittiche usata per le chiavi bitcoin import ecdsa import os from ecdsa.util import string_to_number, number_to_string # secp256k1, _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD L _b = 0x L _a = 0x L _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8L curve_secp256k1 = ecdsa.ellipticcurve.curvefp(_p, _a, _b) generator_secp256k1 = ecdsa.ellipticcurve.point(curve_secp256k1, _Gx, _Gy, _r) oid_secp256k1 = (1, 3, 132, 0, 10) SECP256k1 = ecdsa.curves.curve("secp256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1) ec_order = _r curve = curve_secp256k1 generator = generator_secp256k1 def random_secret(): convert_to_int = lambda array: int("".join(array).encode("hex"), 16) # Collect 256 bits of random data from the OS's cryptographically secure random generator byte_array = os.urandom(32) return convert_to_int(byte_array) def get_point_pubkey(point): if point.y() & 1: key = '03' + '%064x' % point.x() else: key = '02' + '%064x' % point.x() return key.decode('hex') 24

90 def get_point_pubkey_uncompressed(point): key = '04' + \ '%064x' % point.x() + \ '%064x' % point.y() return key.decode('hex') # Generate a new private key. secret = random_secret() print "Secret: ", secret # Get the public key point. point = secret * generator print "EC point:", point print "BTC public key:", get_point_pubkey(point).encode("hex") # Given the point (x, y) we can create the object using: point1 = ecdsa.ellipticcurve.point(curve, point.x(), point.y(), ec_order) assert point1 == point Installando la libreria Python ECDSA ed eseguendo lo script ec_math.py shows the output produced by running this script. NOTE The example above uses os.urandom, which reflects a cryptographically secure random number generator (CSRNG) provided by the underlying operating system. In the case of an UNIX-like operating system such as Linux, it draws from /dev/urandom; and in the case of Windows, calls CryptGenRandom(). If a suitable randomness source is not found, NotImplementedError will be raised. While the random number generator used here is for demonstration purposes, it is not appropriate for generating productionquality bitcoin keys as it is not implemented with sufficient security. 25

91 Example 7. Installando la libreria Python ECDSA ed eseguendo lo script ec_math.py $ # Installa PIP, il package manager di Python $ sudo apt-get install python-pip $ # Installa la libreria Python ECDSA $ sudo pip install ecdsa $ # Esegui lo script $ python ec-math.py Secret: EC point: ( , ) BTC public key: 029ade3effb0a67d5c d797366af428f4a0d5194cb221d807770a I Wallet Wallets are containers for private keys, usually implemented as structured files or simple databases. Another method for making keys is deterministic key generation. Here you derive each new private key, using a one-way hash function from a previous private key, linking them in a sequence. As long as you can re-create that sequence, you only need the first key (known as a seed or master key) to generate them all. In this section we will examine the different methods of key generation and the wallet structures that are built around them. TIP Bitcoin wallets contain keys, not coins. Each user has a wallet containing keys. Wallets are really keychains containing pairs of private/public keys (see Chiavi, Privata e Pubblica). Users sign transactions with the keys, thereby proving they own the transaction outputs (their coins). The coins are stored on the blockchain in the form of transaction-ouputs (often noted as vout or txout). Wallet (Casuali) Nondeterministici In the first bitcoin clients, wallets were simply collections of randomly generated private keys. This type of wallet is called a Type-0 nondeterministic wallet. For example, the Bitcoin Core client pregenerates 100 random private keys when first started and generates more keys as needed, using each key only once. This type of wallet is nicknamed "Just a Bunch Of Keys," or JBOK, and such wallets are being replaced with deterministic wallets because they are cumbersome to manage, back up, and import. The disadvantage of random keys is that if you generate many of them you must keep copies of all of them, meaning that the wallet must be backed up frequently. Each key must be backed up, or the funds it controls are irrevocably lost if the wallet becomes inaccessible. This conflicts directly with the principle of avoiding address re-use, by using each bitcoin address for only one transaction. Address re-use reduces privacy by associating multiple transactions and addresses with each other. A Type-0 nondeterministic wallet is a poor choice of wallet, especially if you want to avoid address re-use 26

92 because that means managing many keys, which creates the need for frequent backups. Although the Bitcoin Core client includes a Type-0 wallet, using this wallet is discouraged by developers of Bitcoin Core. Wallet Type-0 nondeterministico (casuale): una serie di chiavi generate randomicamente shows a nondeterministic wallet, containing a loose collection of random keys. Wallet (Seeded) Deterministici Deterministic, or "seeded" wallets are wallets that contain private keys that are all derived from a common seed, through the use of a one-way hash function. The seed is a randomly generated number that is combined with other data, such as an index number or "chain code" (see Wallet Gerarchici Deterministici (BIP0032/BIP0044)) to derive the private keys. In a deterministic wallet, the seed is sufficient to recover all the derived keys, and therefore a single backup at creation time is sufficient. The seed is also sufficient for a wallet export or import, allowing for easy migration of all the user s keys between different wallet implementations. Figure 8. Wallet Type-0 nondeterministico (casuale): una serie di chiavi generate randomicamente Mnemonic Code Words Mnemonic codes are English word sequences that represent (encode) a random number used as a seed to derive a deterministic wallet. The sequence of words is sufficient to re-create the seed and from there re-create the wallet and all the derived keys. A wallet application that implements deterministic 27

93 wallets with mnemonic code will show the user a sequence of 12 to 24 words when first creating a wallet. That sequence of words is the wallet backup and can be used to recover and re-create all the keys in the same or any compatible wallet application. Mnemonic code words make it easier for users to back up wallets because they are easy to read and correctly transcribe, as compared to a random sequence of numbers. Mnemonic codes are defined in Bitcoin Improvement Proposal 39 (see [bip0039]), currently in Draft status. Note that BIP0039 is a draft proposal and not a standard. Specifically, there is a different standard, with a different set of words, used by the Electrum wallet and predating BIP0039. BIP0039 is used by the Trezor wallet and a few other wallets but is incompatible with Electrum s implementation. BIP0039 definisce la creazione di un codice mnemonico come seed col seguente processo: 1. Crea una sequenza casuale (entropia) da 128 a 256 bit. 2. Create a checksum of the random sequence by taking the first few bits of its SHA256 hash. 3. Add the checksum to the end of the random sequence. 4. Divide the sequence into sections of 11 bits, using those to index a dictionary of 2048 predefined words. 5. Produce 12 to 24 words representing the mnemonic code. Mnemonic codes: entropy and word length shows the relationship between the size of entropy data and the length of mnemonic codes in words. Table 5. Mnemonic codes: entropy and word length Entropy (bits) Checksum (bits) Entropy+checksum Word length Il codice mnemonico rappresenta da 128 a 256 bit, che sono usati per derivare un seed più lungo (512- bit) attraverso l uso della funzione di key-stretching PBKDF2. Il seed risultante è usato per creare un wallet deterministico e tutte le sue chiavi derivate. Tables <xref linkend="table_4-6" xrefstyle="select: labelnumber"/> and <xref linkend="table_4-7" xrefstyle="select: labelnumber"/> show some examples of mnemonic codes and the seeds they produce. Table 6. Codice di entropia mnemonica a 128-bit e seed risultante Entropia di input (128 bit) 0c1e24e d297e14d45f14e1a1a 28

94 Mnemonic (12 parole) Seed (512 bit) army van defense carry jealous true garbage claim echo media make crunch 3338a6d2ee71c7f28eb5b cd46a898463e9 d2d0980f8e80dfbba5b0fa0291e5fb88 8a599b44b93187be6ee3ab5fd3ead7dd646341b2cd b8d08d13bf7 Table 7. Codice di entropia mnemonica a 256-bit e seed risultante Entropia di input (256 bit) Mnemonic (24 words) Seed (512 bit) caff939d32d574753fe684d3c947c dd8423e74abcf8c cake apple borrow silk endorse fitness top denial coil riot stay wolf luggage oxygen faint major edit measure invite love trap field dilemma oblige 3972e432e99040f75ebe13a660110c3e29d131a2c80 8c7ee5f1631d0a977fcf473bee22 fce540af281bf7cdeade0dd2c1c795bd02f1e4049e20 5a c343 Wallet Gerarchici Deterministici (BIP0032/BIP0044) I wallet Deterministici sono stati sviluppati per consentire di derivare chiavi multiple da un singolo "seme" (seed). La forma più avanzata di wallet deterministico è il hierarchical deterministic wallet o HD wallet definito dallo standard BIP0032. I wallet gerarchici deterministici contengono chiavi derivate in una struttura ad albero, tale che da una chiave madre si può far derivare una sequenza di chiavi figlie, e da ognuna di queste si può far derivare una sequenza di chiavi nipoti, e così via, ad una profondità infinita. Questa struttura ad albero è illustrata in Type-2 wallet gerarchico deterministico: una albero di chiavi generate da un singolo seme. 29

95 Figure 9. Type-2 wallet gerarchico deterministico: una albero di chiavi generate da un singolo seme TIP Se si sta implementando un wallet bitcoin, dovrebbe essere costruito come HD wallet seguendo gli standard BIP0032 e BIP0044. Gli HD wallet offrono due importanti vantaggi rispetto alle chiavi casuali (non deterministiche). In primo luogo, la struttura ad albero può essere usata per rappresentare una struttura organizzativa aggiuntiva, ad esempio un ramo specifico di sottochiavi potrebbe essere utilizzato per ricevere i pagamenti in arrivo e un altro ramo per ricevere il resto da pagamenti in uscita. Alcuni rami di chiavi potrebbero essere utilizzate in diversi rami aziendali, assegnando diversi rami a dipartimenti, società affiliate, funzioni specifiche, o categorie contabili. Il secondo vantaggio dei wallet HD è che gli utenti possono creare una sequenza di chiavi pubbliche senza avere accesso alle corrispondenti chiavi private. Questo permette ai wallet HD di essere utilizzati su un server non sicuro o con sola capacità di ricezione, con l emissione di una diversa chiave pubblica per ogni transazione. Le chiavi pubbliche non devono essere precaricate o derivati in anticipo, inoltre il server non deve avere le chiavi private necessarie per spendere i fondi. Creazione del wallet HD da un seme I wallet HD sono creati da un singolo root seed, che è un numero casuale a 128-, 256-, o 512-bit. Tutto il resto nei wallet HD è deterministicamente derivato da questo seme radice, che rende possibile ricreare l intero wallet HD da quel seme in ogni wallet HD compatibile. Questo rende semplice effettuare copie 30

96 di sicurezza, ripristinare, esportare, e importare wallet HD contenenti migliaia o anche milioni di chiavi semplicemente trasferendo solo il seme radice. Il seme radice viene spesso rappresentato da una sequenza mnemonica di parole, come descritto nella precedente sezione Mnemonic Code Words, per rendere più semplice alle persone trascriverle e conservarle. Il processo di creare le chiavi master e il codice master chainper un wallet HD è mostrato in Creare le chiavi master e il chain code da un seme radice. Figure 10. Creare le chiavi master e il chain code da un seme radice Il seme radice è l input nell algoritmo HMAC-SHA512 e l hash risultante viene usato per creare una chiave privata master (m) e un codice master chain. La chiave privata master (m) poi genera una chiave pubblica master corrispondente (M), usando il normale processo di moltiplicazione m * G della curva ellitica che abbiamo visto precedentemente in questo capitolo. Il codice chain viene usato per introdurre entropia nela funzione che crea le chiavi figlie dalle chiavi madre, come vedremo nella prossima sezione. Derivazione delle chiavi private figlie Hierarchical deterministic wallets use a child key derivation (CKD) function to derive children keys from parent keys. Le funzioni di derivazione delle chiavi figlie sono basate su una funzione hash mono-direzionale che combina: Una chiave madre privata o pubblica (chiave ECDSA non compressa) Un seme chiamato chain code (256 bit) Un numero indice (32 bit) Il chain code viene utilizzato per introdurre dati apparentemente casuali nel processo, in modo che non sia sufficiente l indice per derivare altre chiavi figlie. In questo modo, avere una chiave figlia non 31

97 rende possibile trovare le chiavi sorelle, a meno che non si possegga anche il chain code. Il seme iniziale del chain code (alla radice dell albero) è composto da dati casuali, mentre i successivi chain code sono derivate da ogni chain code padre. Questi tre elementi vengono combinati e codificati come hash per generare chiavi figlie, come di seguito. La chiave pubblica principale, il chain code, e il numero indice vengono combinati e codificati con l algoritmo hash HMAC-SHA512 per produrre un hash di 512 bit. L hash risultante viene diviso in due metà. I 256 bit della metà di destra dell' hash risultante diventa il chain code per il figlia. I 256 bit della metà di sinistra dell hash e il numero indice vengono aggiunti alla chiave privata madre per produrre la chiave privata figlia. In << CKDpriv >>, lo vediamo illustrato con il set di indice 0 per produrre lo 0 esimo (primo per indice) figlio del genitore. Estendere una chiave privata madre per creare una chiave privata figlia image::images/msbt_0411.png["childprivatederivation"] Cambiare l indice ci consente di estendere la chiave madre e creare gli altri figli in sequenza, ad esempio Figlio 0, Figlio 1, Figlio 2, ecc. Ogni chiave madre può avere 2 miliardi di chiavi figlie. Ripetendo il processo di un livello verso il basso nell albero, ogni figlia può a sua volta diventare madre e creare le proprie figlie, in un numero infinito di generazioni. Usare le chiavi figlie derivate Le chiavi private figlie sono indistinguibili dalle chiavi non deterministiche (casuali). Poiché la funzione di derivazione è una funzione unidirezionale, la chiave figlia non può essere utilizzata per trovare la chiave madre. La chiave figlia inoltre non può essere usata per trovare eventuali sorelle. Se avete l n esima figlia, non è possibile trovare le sue sorelle, come la figlia n-1 o la figlia n + 1, o qualsiasi altra figlia che fa parte della sequenza. Solo la chiave madre e il codice della catena possono produrre tutte le figlie. Senza il codice della catena della figlia, la chiave figlia non può essere utilizzata neanche per ricavare eventuali nipoti. È necessaria sia la chiave privata figlia che il codice della catena figlia per iniziare un nuovo ramo e derivare nipoti. Quindi la chiave figlia privata di per se stessa per cosa può essere utilizzata? Può essere utilizzata per fare una chiave pubblica e un indirizzo bitcoin. Quindi, può essere utilizzata per firmare transazioni per spendere tutto ciò che è stato pagato su tale indirizzo. TIP Una chiave figlia privata, la corrispondente chiave pubblica, e l indirizzo bitcoin sono tutti indistinguibili da chiavi e indirizzi creati in modo casuale. Il fatto che siano parte di una sequenza non è visibile, all esterno della funzione HD wallet che li ha generati. Una volta create, operano esattamente come chiavi "normali". Chiavi estese Come abbiamo visto in precedenza, la funzione di derivazione delle chiavi può essere utilizzata per 32

98 creare figlie a qualsiasi livello della struttura, sulla base dei tre ingressi: una chiave, un codice a catena, e l indice della figlia desiderata. I due ingredienti essenziali sono il codice della chiave e della catena, e quando combinati vengono chiamati una chiave estesa. Il termine "chiave estesa" potrebbe anche essere pensato come "chiave estensibile" perché tale chiave può essere usata per derivare delle chiavi figlie. Le chiavi estese sono memorizzate e rappresentate semplicemente come la concatenazione della chiave a 256 bit e il codice a catena a 256 bit in una sequenza di 512 bit. Esistono due tipi di chiavi estese. Una chiave privata estesa è la combinazione di una chiave privata e codice catena e può essere utilizzato perderivare chiavi figlie private (e da loro, chiavi figlie pubbliche). Una chiave pubblica estesa è una chiave pubblica e catena codice, che può essere utilizzato per creare chiavi pubbliche figlie, come descritto in Generare una Chiave Pubblica. Pensate a una chiave estesa come alla radice di un ramo nella struttura del portafoglio HD. Con la radice del ramo, è possibile derivare il resto del ramo. La chiave privata estesa può creare un ramo completo, mentre la chiave pubblica estesa può creare solo un ramo di chiavi pubbliche. TIP Una chiave estesa è composta da una chiave privata o pubblica e chain code (codice catena). Una chiave estesa può creare figli, generando un proprio ramo nella struttura ad albero. Condividere una chiave estesa dà accesso a tutto il ramo. Chiavi estese sono codificate utilizzando Base58Check, per poter essere esportate e importate facilmente tra i diversi portafogli compatibili BIP0032. La codifica Base58Check per le chiavi estese utilizza un numero di versione speciale che produce il prefisso "xprv" e "xpub" quando codificato in caratteri a Base58, per renderli facilmente riconoscibili. Poiché la chiave estesa è 512 o 513 bit, è anche molto più lunga di altre stringhe Base58Check codificate che abbiamo visto in precedenza. Ecco un esempio di una chiave privata estesa, codificata in Base58Check: xprv9tyuqv64jt5qs3rstjkxcwkmyugoqp7f3ha1xzg6zgu6u6q9vmnjgr67lctvy5p8oyayal9cawrue9i6gonmk Uga5biW6Hx4tws2six3b9c Ecco la corrispondente chiave pubblica estesa, anche questa codificata in Base58Check: xpub67xpozcx8pe95xvuzlhxzeg6xwxhpgq6qv5cmnfi7cs5mtjj2tgypeqbbs2uar6keceemvkzbplrtjunsdmst weylxhrgpxdp14sk9tjpw9 Derivazione di chiave pubblica figlia Come menzionato precedentemente, una caratteristica molto utile dei wallet gerarchici deterministici è l abilità di derivare chiavi pubbliche figlie da chiavi pubbliche madri, senza avere le chiavi private. Questo ci fornisce due modi di derivare una chiave pubblica: sia dalla chiave privata figlia, o direttamente dalla chiave pubblica madre. 33

99 An extended public key can be used, therefore, to derive all of the public keys (and only the public keys) in that branch of the HD wallet structure. This shortcut can be used to create very secure public-key-only deployments where a server or application has a copy of an extended public key and no private keys whatsoever. That kind of deployment can produce an infinite number of public keys and bitcoin addresses, but cannot spend any of the money sent to those addresses. Meanwhile, on another, more secure server, the extended private key can derive all the corresponding private keys to sign transactions and spend the money. One common application of this solution is to install an extended public key on a web server that serves an ecommerce application. The web server can use the public key derivation function to create a new bitcoin address for every transaction (e.g., for a customer shopping cart). The web server will not have any private keys that would be vulnerable to theft. Without HD wallets, the only way to do this is to generate thousands of bitcoin addresses on a separate secure server and then preload them on the ecommerce server. That approach is cumbersome and requires constant maintenance to ensure that the ecommerce server doesn t "run out" of keys. Another common application of this solution is for cold-storage or hardware wallets. In that scenario, the extended private key can be stored on a paper wallet or hardware device (such as a Trezor hardware wallet), while the extended public key can be kept online. The user can create "receive" addresses at will, while the private keys are safely stored offline. To spend the funds, the user can use the extended private key on an offline signing bitcoin client or sign transactions on the hardware wallet device (e.g., Trezor). Estendere una chiave pubblica madre per creare una chiave pubblica figlia illustrates the mechanism for extending a parent public key to derive child public keys. Figure 11. Estendere una chiave pubblica madre per creare una chiave pubblica figlia Derivazione di chiave figlia Hardened The ability to derive a branch of public keys from an extended public key is very useful, but it comes with a potential risk. Access to an extended public key does not give access to child private keys. However, because the extended public key contains the chain code, if a child private key is known, or 34

100 somehow leaked, it can be used with the chain code to derive all the other child private keys. A single leaked child private key, together with a parent chain code, reveals all the private keys of all the children. Worse, the child private key together with a parent chain code can be used to deduce the parent private key. To counter this risk, HD wallets use an alternative derivation function called hardened derivation, which "breaks" the relationship between parent public key and child chain code. The hardened derivation function uses the parent private key to derive the child chain code, instead of the parent public key. This creates a "firewall" in the parent/child sequence, with a chain code that cannot be used to compromise a parent or sibling private key. The hardened derivation function looks almost identical to the normal child private key derivation, except that the parent private key is used as input to the hash function, instead of the parent public key, as shown in the diagram in Hardened derivation of a child key; omits the parent public key. Figure 12. Hardened derivation of a child key; omits the parent public key Quando la funzione di derivazione delle chiavi private hardened è utilizzata, la chiave privata figlia e il chain code sono completamente diversi da quello che risulterebbe da una normale funzione di derivazione. Il "ramo" risultante di chiavi può essere usato per produrre chiavi pubbliche estese che non siano vulnerabili, perché il chain code contenuto in esse non può essere compromesso per rivelare alcuna chiave privata. La derivazione delle chiavi hardened è quindi utilizzata per creare uno "spazio" nell albero precedente dove le chiavi pubbliche estese sono usate. In simple terms, if you want to use the convenience of an extended public key to derive branches of public keys, without exposing yourself to the risk of a leaked chain code, you should derive it from a hardened parent, rather than a normal parent. As a best practice, the level-1 children of the master 35

101 keys are always derived through the hardened derivation, to prevent compromise of the master keys. Index numbers for normal and hardened derivation The index number used in the derivation function is a 32-bit integer. To easily distinguish between keys derived through the normal derivation function versus keys derived through hardened derivation, this index number is split into two ranges. Index numbers between 0 and (0x0 to 0x7FFFFFFF) are used only for normal derivation. Index numbers between 2 31 and (0x to 0xFFFFFFFF) are used only for hardened derivation. Therefore, if the index number is less than 2 31, that means the child is normal, whereas if the index number is equal or above 2 31, the child is hardened. To make the index number easier to read and display, the index number for hardened children is displayed starting from zero, but with a prime symbol. The first normal child key is therefore displayed as 0, whereas the first hardened child (index 0x ) is displayed as <markup>0'</markup>. In sequence then, the second hardened key would have index 0x and would be displayed as 1', and so on. When you see an HD wallet index i', that means 2<sup>31</sup>+i. Identificatore di una chiave di un wallet HD (path, percorso) Keys in an HD wallet are identified using a "path" naming convention, with each level of the tree separated by a slash (/) character (see Esempi di path in un wallet HD). Private keys derived from the master private key start with "m". Public keys derived from the master public key start with "M". Therefore, the first child private key of the master private key is m/0. The first child public key is M/0. The second grandchild of the first child is m/0/1, and so on. La "discendenza" di una chiave si può leggere da destra verso sinistra, fino a che non si raggiunge la master key dalla quale è stata derivata. Per esempio, l identificatore m/x/y/z descrive la chiave che è la z-esima figlia della chiave m/x/y, la quale è la y-esima figlia della chiave m/x, che è la x-esima figlia di m. Table 8. Esempi di path in un wallet HD path HD Chiave descritta m/0 The first (0) child private key from the master private key (m) m/0/0 m/0'/0 m/1/0 The first grandchild private key of the first child (m/0) The first normal grandchild of the first hardened child (m/0') La prima chiave privata "nipote" derivata dal secondo "figlio" (m/1) 36

102 path HD M/23/17/0/0 Chiave descritta The first great-great-grandchild public key of the first great-grandchild of the 18th grandchild of the 24th child Navigando la struttura ad albero degli HD wallet The HD wallet tree structure offers tremendous flexibility. Each parent extended key can have 4 billion children: 2 billion normal children and 2 billion hardened children. Each of those children can have another 4 billion children, and so on. The tree can be as deep as you want, with an infinite number of generations. With all that flexibility, however, it becomes quite difficult to navigate this infinite tree. It is especially difficult to transfer HD wallets between implementations, because the possibilities for internal organization into branches and subbranches are endless. Two Bitcoin Improvement Proposals (BIPs) offer a solution to this complexity, by creating some proposed standards for the structure of HD wallet trees. BIP0043 proposes the use of the first hardened child index as a special identifier that signifies the "purpose" of the tree structure. Based on BIP0043, an HD wallet should use only one level-1 branch of the tree, with the index number identifying the structure and namespace of the rest of the tree by defining its purpose. For example, an HD wallet using only branch m/i'/ is intended to signify a specific purpose and that purpose is identified by index number "i". Extending that specification, BIP0044 proposes a multiaccount structure as "purpose" number 44' under BIP0043. All HD wallets following the BIP0044 structure are identified by the fact that they only used one branch of the tree: m/44'/. BIP0044 specifica la struttura consistente di cinque livelli ad albero predefiniti: m / purpose' / coin_type' / account' / change / address_index The first-level "purpose" is always set to 44'. The second-level "coin_type" specifies the type of cryptocurrency coin, allowing for multicurrency HD wallets where each currency has its own subtree under the second level. There are three currencies defined for now: Bitcoin is m/44'/0', Bitcoin Testnet is <markup>m/44'/1'</markup>; and Litecoin is <markup>m/44'/2'</markup>. The third level of the tree is "account," which allows users to subdivide their wallets into separate logical subaccounts, for accounting or organizational purposes. For example, an HD wallet might contain two bitcoin "accounts": <markup>m/44'/0'/0'</markup> and <markup>m/44'/0'/1'</markup>. Each account is the root of its own subtree. On the fourth level, "change," an HD wallet has two subtrees, one for creating receiving addresses and one for creating change addresses. Note that whereas the previous levels used hardened derivation, this level uses normal derivation. This is to allow this level of the tree to export extended public keys for use in a nonsecured environment. Usable addresses are derived by the HD wallet as children of the fourth level, making the fifth level of the tree the "address_index." For example, the third receiving address for bitcoin payments in the primary account would be M/44'/0'/0'/0/2. BIP0044 Esempi della 37

103 struttura dei HD wallet shows a few more examples. Table 9. BIP0044 Esempi della struttura dei HD wallet path HD M/44'/0'/0'/0/2 M/44'/0'/3'/1/14 m/44'/2'/0'/0/1 Chiave descritta La terza chiave pubblica ricevente per l account bitcoin primario La quindicesima chiave pubblica dell indirizzodel-resto per il quarto account bitcoin The second private key in the Litecoin main account, for signing transactions Esperimenti con gli HD wallet utilizzando Bitcoin Explorer Using the Bitcoin Explorer command-line tool introduced in [ch03_bitcoin_client], you can experiment with generating and extending BIP0032 deterministic keys, as well as displaying them in different formats: $ bx seed bx hd-new > m # crea una master private key da un seed e la salva in un file "m" $ cat m # mostra la chiave privata master estesa xprv9s21zrqh143k38iq9y5p6qob8c75te71nfpyqpdfgvzghdt39dhpfpovvtwzargy5upwv7rpeghs7cvdg fisjljjbugkgcjryu7rggss8xa $ cat m bx hd-public # genera la chiave pubblica estesa M/0 xpub67xpozcx8pe95xvuzlhxzeg6xwxhpgq6qv5cmnfi7cs5mtjj2tgypeqbbs2uar6keceemvkzbplrtjuns DMstweyLXhRgPxdp14sk9tJPW9 $ cat m bx hd-private # genera la chiave privata m/0 estesa xprv9tyuqv64jt5qs3rstjkxcwkmyugoqp7f3ha1xzg6zgu6u6q9vmnjgr67lctvy5p8oyayal9cawrue9i6g onmkuga5biw6hx4tws2six3b9c $ cat m bx hd-private bx hd-to-wif # mostra la chiave privata di m/0 come WIF L1pbvV86crAGoDzqmgY85xURkz3c435Z9nirMt52UbnGjYMzKBUN $ cat m bx hd-public bx hd-to-address # mostra l'indirizzo bitcoin di M/0 1CHCnCjgMNb6digimckNQ6TBVcTWBAmPHK $ cat m bx hd-private bx hd-private --index 12 --hard bx hd-private --index 4 # genera m/0/12'/4 xprv9yl8ndfdpvedwjenf18oihguruj8jhmvrqqd97yqhetcr3lceh53q5pxpklsy2kraqgwos6yzblatrzry UeAkRPe1kLR1P6Mn7jUrXFquUt Chiavi avanzate e Indirizzi Nelle sezioni seguenti osserveremo le forme avanzate di chiavi e indirizzi quali, chiavi private criptate, indirizzi script e multifirma, vanity address e paper wallet. 38

104 Chiave Privata Criptata (BIP0038) Private keys must remain secret. The need for confidentiality of the private keys is a truism that is quite difficult to achieve in practice, because it conflicts with the equally important security objective of availability. Keeping the private key private is much harder when you need to store backups of the private key to avoid losing it. A private key stored in a wallet that is encrypted by a password might be secure, but that wallet needs to be backed up. At times, users need to move keys from one wallet to another to upgrade or replace the wallet software, for example. Private key backups might also be stored on paper (see I Paper Wallet) or on external storage media, such as a USB flash drive. But what if the backup itself is stolen or lost? These conflicting security goals led to the introduction of a portable and convenient standard for encrypting private keys in a way that can be understood by many different wallets and bitcoin clients, standardized by Bitcoin Improvement Proposal 38 or BIP0038 (see [bip0038]). BIP0038 proposes a common standard for encrypting private keys with a passphrase and encoding them with Base58Check so that they can be stored securely on backup media, transported securely between wallets, or kept in any other conditions where the key might be exposed. The standard for encryption uses the Advanced Encryption Standard (AES), a standard established by the National Institute of Standards and Technology (NIST) and used broadly in data encryption implementations for commercial and military applications. A BIP0038 encryption scheme takes as input a bitcoin private key, usually encoded in the Wallet Import Format (WIF), as a Base58Check string with a prefix of "5". Additionally, the BIP0038 encryption scheme takes a passphrase a long password usually composed of several words or a complex string of alphanumeric characters. The result of the BIP0038 encryption scheme is a Base58Check-encoded encrypted private key that begins with the prefix 6P. If you see a key that starts with 6P, that means it is encrypted and requires a passphrase in order to convert (decrypt) it back into a WIF-formatted private key (prefix 5) that can be used in any wallet. Many wallet applications now recognize BIP0038- encrypted private keys and will prompt the user for a passphrase to decrypt and import the key. Thirdparty applications, such as the incredibly useful browser-based Bit Address (Wallet Details tab), can be used to decrypt BIP0038 keys. The most common use case for BIP0038 encrypted keys is for paper wallets that can be used to back up private keys on a piece of paper. As long as the user selects a strong passphrase, a paper wallet with BIP0038 encrypted private keys is incredibly secure and a great way to create offline bitcoin storage (also known as "cold storage"). Prova le chiavi criptate nella Esempio di chiave privata codificata BIP0038 usando bitaddress.org per vedere come ottenere la chiave decriptata inserendo la passphrase. Table 10. Esempio di chiave privata codificata BIP0038 Private Key (WIF) Passphrase 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2Jpbnk eyhfsyb1jcn MyTestPassphrase 39

105 Chiave Criptata (BIP0038) 6PRTHL6mWa48xSopbU1cKrVjpKbBZxcLRRCdctL J3z5yxE87MobKoXdTsJ Pay-to-Script Hash (P2SH) e Indirizzi Multi-Sig As we know, traditional bitcoin addresses begin with the number 1 and are derived from the public key, which is derived from the private key. Although anyone can send bitcoin to a 1 address, that bitcoin can only be spent by presenting the corresponding private key signature and public key hash. Bitcoin addresses that begin with the number 3 are pay-to-script hash (P2SH) addresses, sometimes erroneously called multi-signature or multi-sig addresses. They designate the beneficiary of a bitcoin transaction as the hash of a script, instead of the owner of a public key. The feature was introduced in January 2012 with Bitcoin Improvement Proposal 16, or BIP0016 (see [bip0016]), and is being widely adopted because it provides the opportunity to add functionality to the address itself. Unlike transactions that "send" funds to traditional 1 bitcoin addresses, also known as pay-to-public-keyhash (P2PKH), funds sent to 3 addresses require something more than the presentation of one public key hash and one private key signature as proof of ownership. The requirements are designated at the time the address is created, within the script, and all inputs to this address will be encumbered with the same requirements. A pay-to-script hash address is created from a transaction script, which defines who can spend a transaction output (for more detail, see [p2sh]). Encoding a pay-to-script hash address involves using the same double-hash function as used during creation of a bitcoin address, only applied on the script instead of the public key: script hash = RIPEMD160(SHA256(script)) The resulting "script hash" is encoded with Base58Check with a version prefix of 5, which results in an encoded address starting with a 3. An example of a P2SH address is 3F6i6kwkevjR7AsAd4te2YB2zZyASEm1HM, which can be derived using the Bitcoin Explorer commands script-encode, sha256, ripemd160, and base58check-encode (see [libbitcoin]) as follows: $ echo dup hash160 [ 89abcdefabbaabbaabbaabbaabbaabbaabbaabba ] equalverify checksig > script $ bx script-encode < script bx sha256 bx ripemd160 bx base58check-encode --version 5 3F6i6kwkevjR7AsAd4te2YB2zZyASEm1HM TIP P2SH is not necessarily the same as a multi-signature standard transaction. A P2SH address most often represents a multi-signature script, but it might also represent a script encoding other types of transactions. 40

106 Indirizzi Multi-firma e P2SH Currently, the most common implementation of the P2SH function is the multi-signature address script. As the name implies, the underlying script requires more than one signature to prove ownership and therefore spend funds. The bitcoin multi-signature feature is designed to require M signatures (also known as the threshold ) from a total of N keys, known as an M-of-N multi-sig, where M is equal to or less than N. For example, Bob the coffee shop owner from [ch01_intro_what_is_bitcoin] could use a multi-signature address requiring 1-of-2 signatures from a key belonging to him and a key belonging to his spouse, ensuring either of them could sign to spend a transaction output locked to this address. This would be similar to a joint account as implemented in traditional banking where either spouse can spend with a single signature. Or Gopesh, the web designer paid by Bob to create a website, might have a 2-of-3 multi-signature address for his business that ensures that no funds can be spent unless at least two of the business partners sign a transaction. Esploreremo come creare transazioni che spendono fondi da indirizzi P2SH (e multi-signature) in [transactions]. Vanity Address Vanity addresses are valid bitcoin addresses that contain human-readable messages. For example, 1LoveBPzzD72PUXLzCkYAtGFYmK5vYNR33 is a valid address that contains the letters forming the word "Love" as the first four Base-58 letters. Vanity addresses require generating and testing billions of candidate private keys, until one derives a bitcoin address with the desired pattern. Although there are some optimizations in the vanity generation algorithm, the process essentially involves picking a private key at random, deriving the public key, deriving the bitcoin address, and checking to see if it matches the desired vanity pattern, repeating billions of times until a match is found. Once a vanity address matching the desired pattern is found, the private key from which it was derived can be used by the owner to spend bitcoins in exactly the same way as any other address. Vanity addresses are no less or more secure than any other address. They depend on the same Elliptic Curve Cryptography (ECC) and Secure Hash Algorithm (SHA) as any other address. You can no more easily find the private key of an address starting with a vanity pattern than you can any other address. Nel [ch01_intro_what_is_bitcoin], abbiamo introdotto Eugenia, direttrice di un associazione no-profit che opera nelle Filippine. Mettiamo che Eugenia sta organizzando una raccolta fondi in bitcoin e voglia usare un bitcoin vanity address per pubblicizzare la raccolta fondi. Eugenia creerà un vanity address che inizia con "1Kids" per promuovere la raccolta fondii della no-profit che si occupa di bambini bisognosi. Vediamo come questo vanity address sarà generato e come la no-profit di Eugenia si dovrà comportare riguardo alla sicurezza. Generare vanity address It s important to realize that a bitcoin address is simply a number represented by symbols in the Base58 alphabet. The search for a pattern like "1Kids" can be seen as searching for an address in the range from 1Kids to 1Kidszzzzzzzzzzzzzzzzzzzzzzzzzzzzz. There are approximately (approximately 1.4 * ) addresses in that range, all starting with "1Kids". La 41

107 gamma di vanity address che iniziano con "1Kids" shows the range of addresses that have the prefix 1Kids. Table 11. La gamma di vanity address che iniziano con "1Kids" Da 1Kids Kids Kids A 1Kidszzzzzzzzzzzzzzzzzzzzzzzzzzzzz Let s look at the pattern "1Kids" as a number and see how frequently we might find this pattern in a bitcoin address (see La frequenza di un vanity pattern (1KidsCharity) e il tempo-di-ricerca su un PC fisso). An average desktop computer PC, without any specialized hardware, can search approximately 100,000 keys per second. Table 12. La frequenza di un vanity pattern (1KidsCharity) e il tempo-di-ricerca su un PC fisso Lunghezza Pattern Frequenza Tempo medio di ricerca 1 1K 1 su 58 chiavi < 1 millisecondi 2 1Ki 1 su 3, millisecondi 3 1Kid 1 su 195,000 < 2 secondi 4 1Kids 1 su 11 million 1 minuto 5 1KidsC 1 su 656 milioni 1 ora 6 1KidsCh 1 su 38 miliardi 2 giorni 7 1KidsCha 1 su 2.2 mila miliardi 3 4 mesi 8 1KidsChar 1 su 128 mila miliardi anni 9 1KidsChari 1 su 7 milioni di miliardi 800 anni 10 1KidsCharit 1 su 400 milioni di miliardi 11 1KidsCharity 1 su 23 mila milioni di miliardi 46,000 anni 2.5 milioni di anni As you can see, Eugenia won t be creating the vanity address "1KidsCharity" any time soon, even if she had access to several thousand computers. Each additional character increases the difficulty by a factor of 58. Patterns with more than seven characters are usually found by specialized hardware, such as custom-built desktops with multiple graphical processing units (GPUs). These are often repurposed bitcoin mining "rigs" that are no longer profitable for bitcoin mining but can be used to find vanity 42

108 addresses. Vanity searches on GPU systems are many orders of magnitude faster than on a generalpurpose CPU. Another way to find a vanity address is to outsource the work to a pool of vanity miners, such as the pool at Vanity Pool. A pool is a service that allows those with GPU hardware to earn bitcoin searching for vanity addresses for others. For a small payment (0.01 bitcoin or approximately $5 at the time of this writing), Eugenia can outsource the search for a seven-character pattern vanity address and get results in a few hours instead of having to run a CPU search for months. Generating a vanity address is a brute-force exercise: try a random key, check the resulting address to see if it matches the desired pattern, repeat until successful. Miner di vanity address shows an example of a "vanity miner," a program designed to find vanity addresses, written in C++. The example uses the libbitcoin library, which we introduced in [alt_libraries]. Example 8. Miner di vanity address #include <bitcoin/bitcoin.hpp> // The string we are searching for const std::string search = "1kid"; // Generate a random secret key. A random 32 bytes. bc::ec_secret random_secret(std::default_random_engine& engine); // Extract the Bitcoin address from an EC secret. std::string bitcoin_address(const bc::ec_secret& secret); // Case insensitive comparison with the search string. bool match_found(const std::string& address); int main() { // random_device on Linux uses "/dev/urandom" // CAUTION: Depending on implementation this RNG may not be secure enough! // Do not use vanity keys generated by this example in production std::random_device random; std::default_random_engine engine(random()); // Loop continuously... while (true) { // Generate a random secret. bc::ec_secret secret = random_secret(engine); // Get the address. std::string address = bitcoin_address(secret); // Does it match our search string? (1kid) if (match_found(address)) { // Success! 43

109 } std::cout << "Found vanity address! " << address << std::endl; std::cout << "Secret: " << bc::encode_hex(secret) << std::endl; return 0; } } // Should never reach here! return 0; bc::ec_secret random_secret(std::default_random_engine& engine) { // Create new secret... bc::ec_secret secret; // Iterate through every byte setting a random value... for (uint8_t& byte: secret) byte = engine() % std::numeric_limits<uint8_t>::max(); // Return result. return secret; } std::string bitcoin_address(const bc::ec_secret& secret) { // Convert secret to pubkey... bc::ec_point pubkey = bc::secret_to_public_key(secret); // Finally create address. bc::payment_address payaddr; bc::set_public_key(payaddr, pubkey); // Return encoded form. return payaddr.encoded(); } bool match_found(const std::string& address) { auto addr_it = address.begin(); // Loop through the search string comparing it to the lower case // character of the supplied address. for (auto it = search.begin(); it!= search.end(); ++it, ++addr_it) if (*it!= std::tolower(*addr_it)) return false; // Reached end of search string, so address matches. return true; } 44

110 NOTE The example above uses std::random_device. Depending on the implementation it may reflect a cryptographically secure random number generator (CSRNG) provided by the underlying operating system. In the case of UNIX-like operating system such as Linux, it draws from /dev/urandom. While the random number generator used here is for demonstration purposes, it is not appropriate for generating production-quality bitcoin keys as it is not implemented with sufficient security. The example code must be compiled using a C compiler and linked against the libbitcoin library (which must be first installed on that system). To run the example, run the vanity-miner++ executable with no parameters (see Compilare e eseguire l esempio di vanity-miner) and it will attempt to find a vanity address starting with "1kid". Example 9. Compilare e eseguire l esempio di vanity-miner $ # Compila il codice con g++ $ g++ -o vanity-miner vanity-miner.cpp $(pkg-config --cflags --libs libbitcoin) $ # Esegui l'esempio $./vanity-miner Found vanity address! 1KiDzkG4MxmovZryZRj8tK81oQRhbZ46YT Secret: 57cc268a05f83a23ac9d930bc8565bac4e277055f4794cbd1a39e5e71c038f3f $ # Eseguilo nuovamente per ottenere un risultato differente $./vanity-miner Found vanity address! 1Kidxr3wsmMzzouwXibKfwTYs5Pau8TUFn Secret: 7f65bbbbe6d8caae74a0c6a0d2d7b5c6663d71b a1a2cf34c04b2a623 # Utilizza "time" per conoscere il tempo necessario per trovare un risultato $ time./vanity-miner Found vanity address! 1KidPWhKgGRQWD5PP5TAnGfDyfWp5yceXM Secret: 2a802e7a53d8aa237cd059377b616d2bfcfa4b0140bc85fa008f2d3d4b real 0m8.868s user 0m8.828s sys 0m0.035s Il codice d esempio impiegherà pochi secondi per trovare una corrispondenza per il pattern "kid", come possiamo vedere quando usiamo il comando Unix time per misurare il tempo d esecuzione. Puoi cambiare il pattern di ricerca nei codice sorgente e vedere quanto più tempo impiegano dei pattern di quattro o cinque caratteri! Sicurezza dei vanity address Vanity addresses can be used to enhance and to defeat security measures; they are truly a doubleedged sword. Used to improve security, a distinctive address makes it harder for adversaries to substitute their own address and fool your customers into paying them instead of you. Unfortunately, vanity addresses also make it possible for anyone to create an address that resembles any random 45

111 address, or even another vanity address, thereby fooling your customers. Eugenia potrebbe pubblicare un indirizzo generato casualmente (e.g., 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy) a cui altri utenti possono inviare le loro donazioni. Oppure, potrebbe generare un vanity address che inizi con 1Kids, per renderlo più riconoscibile. In both cases, one of the risks of using a single fixed address (rather than a separate dynamic address per donor) is that a thief might be able to infiltrate your website and replace it with his own address, thereby diverting donations to himself. If you have advertised your donation address in a number of different places, your users may visually inspect the address before making a payment to ensure it is the same one they saw on your website, on your , and on your flyer. In the case of a random address like 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy, the average user will perhaps inspect the first few characters "1J7mdg" and be satisfied that the address matches. Using a vanity address generator, someone with the intent to steal by substituting a similar-looking address can quickly generate addresses that match the first few characters, as shown in Generando un vanity address che sia simile a un indirizzo casuale. Table 13. Generando un vanity address che sia simile a un indirizzo casuale Indirizzo Casuale Originario Vanity (match di 4 caratteri) Vanity (match di 5 caratteri) Vanity (match di 6 caratteri) 1J7mdg5rbQyUHENYdx39WVWK7fsLpEoXZy 1J7md1QqU4LpctBetHS2ZoyLV5d6dShhEy 1J7mdgYqyNd4ya3UEcq31Q7sqRMXw2XZ6n 1J7mdg5WxGENmwyJP9xuGhG5KRzu99BBCX So does a vanity address increase security? If Eugenia generates the vanity address 1Kids33q44erFfpeXrmDSz7zEqG2FesZEN, users are likely to look at the vanity pattern word <em>and a few characters beyond</em>, for example noticing the "1Kids33" part of the address. That would force an attacker to generate a vanity address matching at least six characters (two more), expending an effort that is 3,364 times (58 58) higher than the effort Eugenia expended for her fourcharacter vanity. Essentially, the effort Eugenia expends (or pays a vanity pool for) "pushes" the attacker into having to produce a longer pattern vanity. If Eugenia pays a pool to generate an 8- character vanity address, the attacker would be pushed into the realm of 10 characters, which is infeasible on a personal computer and expensive even with a custom vanity-mining rig or vanity pool. What is affordable for Eugenia becomes unaffordable for the attacker, especially if the potential reward of fraud is not high enough to cover the cost of the vanity address generation. I Paper Wallet Paper wallets are bitcoin private keys printed on paper. Often the paper wallet also includes the corresponding bitcoin address for convenience, but this is not necessary because it can be derived from the private key. Paper wallets are a very effective way to create backups or offline bitcoin storage, also known as "cold storage." As a backup mechanism, a paper wallet can provide security against the loss of key due to a computer mishap such as a hard drive failure, theft, or accidental deletion. As a "cold storage" mechanism, if the paper wallet keys are generated offline and never stored on a 46

112 computer system, they are much more secure against hackers, key-loggers, and other online computer threats. I paper wallet sono disponibili in molte forme, dimensioni e design, ma essenzialmente sono solo una chiave e un indirizzo stampati su carta. La forma più semplice di paper wallet un foglio stampato con l indirizzo bitcoin e la chiave privata. mostra la forma più semplice di un paper wallet. Table 14. La forma più semplice di paper wallet un foglio stampato con l indirizzo bitcoin e la chiave privata. Indirizzo Pubblico 1424C2F4bC9JidNjjTUZCbUxv6Sa1Mt62x Chiave Privata (WIF) 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2Jpbnk eyhfsyb1jcn Paper wallets can be generated easily using a tool such as the client-side JavaScript generator at bitaddress.org. This page contains all the code necessary to generate keys and paper wallets, even while completely disconnected from the Internet. To use it, save the HTML page on your local drive or on an external USB flash drive. Disconnect from the Internet and open the file in a browser. Even better, boot your computer using a pristine operating system, such as a CD-ROM bootable Linux OS. Any keys generated with this tool while offline can be printed on a local printer over a USB cable (not wirelessly), thereby creating paper wallets whose keys exist only on the paper and have never been stored on any online system. Put these paper wallets in a fireproof safe and "send" bitcoin to their bitcoin address, to implement a simple yet highly effective "cold storage" solution. Un esempio di un paper wallet semplice da bitaddress.org shows a paper wallet generated from the bitaddress.org site. Figure 13. Un esempio di un paper wallet semplice da bitaddress.org The disadvantage of the simple paper wallet system is that the printed keys are vulnerable to theft. A thief who is able to gain access to the paper can either steal it or photograph the keys and take control of the bitcoins locked with those keys. A more sophisticated paper wallet storage system uses BIP0038 encrypted private keys. The keys printed on the paper wallet are protected by a passphrase that the owner has memorized. Without the passphrase, the encrypted keys are useless. Yet, they still are superior to a passphrase-protected wallet because the keys have never been online and must be 47

113 physically retrieved from a safe or other physically secured storage. Un esempio di un paper wallet protetto da password dal sito bitaddress.org. La passphrase è "test." shows a paper wallet with an encrypted private key (BIP0038) created on the bitaddress.org site. Figure 14. Un esempio di un paper wallet protetto da password dal sito bitaddress.org. La passphrase è "test." Although you can deposit funds into a paper wallet several times, you should withdraw all funds only once, spending everything. This is because in the process of unlocking and spending funds some wallets might generate a change address if you spend less than the whole amount. Additionally, if the computer you use to sign the transaction is compromised, you risk exposing the private key. By spending the entire balance of a paper wallet only once, you reduce the risk of key compromise. If you need only a small amount, send any remaining funds to a new paper wallet in the same transaction. Esistono paper wallet esistono in molte dimensioni e forme, e con diverse funzionalità. Alcuni sono fatti per essere dati come regalo e hanno temi particolari come per esempoo temi di Natale e Capodanno. Altri sono stati progettati per essere conservati in una cassetta di sicurezza o cassaforte con la chiave privata nascosta in qualche maniera, sia con un etichetta opaca grattabile, o piegata e sigillata con un foglio di alluminio adesivo a prova di apertura inattesa. TODO 48

114 Figure 15. Un esempio di un paper wallet da bitcoinpaperwallet.com con la private key stampata su una parte pieghevole. Figure 16. Il paper wallet di bitcoinpaperwallet.com con la chiave privata nascosta. Other designs feature additional copies of the key and address, in the form of detachable stubs similar to ticket stubs, allowing you to store multiple copies to protect against fire, flood, or other natural disasters. Figure 17. Un esempio di un paper wallet con copie aggiuntive di un backup "campione". 49

115 Transazioni Introduzione Le transazioni sono la parte più importante del sistema bitcoin. Tutto il resto in bitcoin è progettato per assicurare che le transazioni possano essere create, propagate nel network, validate e infine aggiunte al registro globale delle transazioni (la blockchain). Le transazioni sono strutture dati che codificano il valore del trasferimento tra partecipanti nel sistema bitcoin. Ogni transazione è un dato pubblico nella blockchain di bitcoin, il registro contabile globale a partita doppia (double-entry bookkeeping). In questo capitolo esamineremo le varie forme di transazione, cosa contengono, come crearle, come sono verificate e come diventano parte del registro permanente di tutte le transazioni. Ciclo Vitale delle Transazioni Il ciclo di vita di una transazione inizia con la sua creazione, anche conosciuta come originazione. La transazione è poi firmata con una o più firme che indicano l autorizzazione a spendere i fondi riferiti dalla transazione. La transazione è poi trasmessa sul network bitcoin, dove ogni nodo del network (partecipante) valida e propaga la transazione fino che non arriva (quasi a) ogni nodo del network. Infine, la transazione è verificata da un nodo miner e inclusa in un blocco di transazioni che è registrato nella blockchain. Una volta registrata sulla blockchain e confermata da un numero di blocchi susseguenti sufficienti (conferme), la transazione è parte permanente del registro bitcoin ed è accettata come valida da tutti i partecipanti. I fondi assegnati al nuovo proprietario dalla transazione possono essere spesi in una nuova transazione, estendendo la catena di passaggi di proprietà e iniziando nuovamente il ciclo-vita di una transazione. Creare Transazioni In un certo senso si potrebbe pensare ad una transazione come se fosse un assegno. Come un assegno, una transazione è uno strumento che esprime l intento di trasferire valuta e non è visibile al sistema finanziario fino a che non è immesso nel sistema affinchè sia eseguito. Come per gli assegni, chi effettua la transazione non deve essere per forza colui che firma la transazione. Transactions can be created online or offline by anyone, even if the person creating the transaction is not an authorized signer on the account. For example, an accounts payable clerk might process payable checks for signature by the CEO. Similarly, an accounts payable clerk can create bitcoin transactions and then have the CEO apply digital signatures to make them valid. Whereas a check references a specific account as the source of the funds, a bitcoin transaction references a specific previous transaction as its source, rather than an account. Once a transaction has been created, it is signed by the owner (or owners) of the source funds. If it is properly formed and signed, the signed transaction is now valid and contains all the information 1

116 needed to execute the transfer of funds. Finally, the valid transaction has to reach the bitcoin network so that it can be propagated until it reaches a miner for inclusion in the pubic ledger (the blockchain). Trasmettere Transazioni sulla Rete Bitcoin Per prima cosa, una transazione deve essere consegnata al network bitcoin così che possa essere propagata e inclusa nella blockchain. In sostanza, una transazione bitcoin è solamente da 300 a 400 byte di dati e deve raggiungere uno delle decine di migliaia di nodi bitcoin. I mittenti non devono fidarsi dei nodi che usano per pubblicare la transazione, fintanto che ne usino più di uno per assicurarsi che si propaghi. I nodi non devono riporre fiducia nel mittente o stabilire l'"identità" di esso. Visto che la transazione è firmata e non contiene nessuna informazione confidenziale, come chiavi private o credenziali, essa può essere pubblicata apertamente usando qualsiasi rete sottostante per il trasporto di dati che sia conveniente. A differenza delle transazioni delle carte di credito, per esempio, che contengono informazioni sensibili e possono essere trasmesse solo su reti protette, una transazione bitcoin può essere inviata su qualsiasi rete. Fin quando la transazione può raggiungere un nodo bitcoin che la possa propagare nella rete bitcoin, questo è sufficiente, non importa come sia trasportata al primo nodo. Le transazioni bitcoin possono per questo essere trasmesse al network bitcoin su reti insicure come le reti WiFi, Bluetooth, NFC, Chirp, codici a barre, o copiando e incollando attraverso un form web. In casi estremi, una transazione bitcoin può essere trasmessa attraverso packet radio, trasmissione satellitare, onde corte utilizzando una trasmissione burst a onde corte, ad ampio spettro, o con frequency hopping per evitare di essere rivelata e distrubata (jamming). Una transazione bitcoin può anche essere codificata come faccine (smileys, emoticon) e postata in un forum pubblico o inviata come messaggio testuale o Skype chat. Bitcoin ha trasformato i soldi in una struttura dati, facendo in modo che sia praticamente impossibile impedire a qualcuno di creare e eseguire una transazione bitcoin. Propagare Transazioni sulla Rete Bitcoin Una volta che una transazione bitcoin è inviata a qualsiasi nodo connesso alla rete bitcoin, quella transazione sarà validata da quel nodo. Se valida, quel nodo la propagherà agli altri nodi a cui è connesso, e un messaggio di conferma verrà ritornato sincronamente all originatore. Se la transazione è invalida, il nodo la respingerà e sincronamente ritornerà un messaggio rigettandola all originatore. La rete bitcoin è una rete peer-to-peer, questo significa che ogni nodo bitcoin è connesso con un po di altri nodi bitcoin che scopre durante l avvio del programma attraverso il protocollo peer-to-peer. L intero network forma una maglia (mesh) connessa in modo lasso senza una tipologia fissa o struttura predefinita, rendendo tutti i nodi peer alla pari. I messaggi, includendo transazioni e blocchi, sono propagati da ogni nodo a tutti i peer a cui sono connessi, un processo chiamato "flooding" (inondazione). Una nuova transizione validata iniettata dentro un qualsiasi nodo della rete sarà inviata a tutti i nodi connessi ad esso (vicini), ognuno di essi invierà la transazione a tutti i suoi vicini, e così via. In questo modo, nel giro di pochi secondi una transazione valida si propagherà in un onda che si espanderà esponenzialmente attraverso il network fino a che tutti i nodi non l avranno ricevuta. The bitcoin network is designed to propagate transactions and blocks to all nodes in an efficient and resilient manner that is resistant to attacks. To prevent spamming, denial-of-service attacks, or other 2

117 nuisance attacks against the bitcoin system, every node independently validates every transaction before propagating it further. A malformed transaction will not get beyond one node. The rules by which transactions are validated are explained in more detail in [tx_verification]. Struttura della Transazione Una transazioni è una struttura dati che codifica e trasferisce un valore da una fonte di fondi, chiamata un input, a una destinazione, chiamata un output. Gli input di transazione e gli output non sono relazionati a nessun account o identità. Al contrario, dovresti immaginarteli come pezzi/somme di bitcoin (allucchettati e) protetti tramite una chiave segreta che solo il proprietario, o la persona che conosce la chiave, può sbloccare. Una transazione contiene un certo numero di campi, come mostrato in La struttura di una transazione. Table 1. La struttura di una transazione Dimensione Campo Descrizione 4 bytes Versione Specifica quale regole segue la seguente transazione 1 9 bytes (VarInt) Input Counter Quanti input sono inclusi Variable Inputs Uno o più input di transazione 1 9 bytes (VarInt) Output Counter Quanti output sono inclusi Variable Outputs Uno o più output di transazione 4 bytes Locktime Un Unix timestamp o numero del blocco Locktime di Transazione Il locktime, conosciuto anche come nlocktime dal nome della variabile usata nel client di riferimento (reference client), definisce il primo tempo (timestamp) in cui una transazione è considerata valida e può essere trasmessa alla rete o aggiunta alla blockchain. E' impostata a zero in molte transazioni per indicare la propagazione e l esecuzione immediata. Se il locktime non è impostato a zero e sotto 500 milioni, è interpretato come una block height, questo sta a significare che la transazione non è valida e non sarà trasmessa attraverso o inclusa nella blockchain prima della block height specificata. Se è oltre i 500 milioni, è interpretato come un timestamp Unix Epoch (secondi dal 1-Gen-1970) e la transazione non saraà valida prima del tempo specificato. Le transazioni con locktime che specificano un blocco futuro o un timestamp devono essere create dal sistema originante e trasmesse al network bitcoin solo dopo che esse sono divenute valide. L uso del locktime è equivalente al postdatare un assegno. 3

118 Output e Input di una Transazione I mattoni fondamentali di una transazione bitcoin sono gli output di transazione non spesi (unspent transaction outputs), o UTXO. Gli UTXO sono frammenti indivisibili di valuta bitcoin "allucchettati" su di un proprietario specifico, registrati sulla blockchain, e riconosciuti come unità di valuta da tutto il network. Il network bitcoin traccia tutti gli UTXO disponibili (non spesi) che attualmente si contano essere nell ordine dei milioni. Ogniqualvolta un utente riceve bitcoin, quella somma è registrata dentro la blockchain come UTXO. Pertanto, i bitcoin di un utente potrebbero essere sparpagliati in UTXO nelle centinaia di transazioni e centinaia di blocchi. In effetti, non c è un qualcosa come un saldo salvato di un indirizzo bitcoin o account; ci sono solo UTXO disseminati, protetti sugli specifici proprietari. Il concetto di un saldo bitcoin di un utente è un costrutto derivato creato dall applicazione wallet. Il wallet calcola il saldo dell utente scansionando la blockchain e aggregando tutti gli UTXO appartenenti a quell utente. TIP Non ci sono bilanci in bitcoin; ci sono solo output di transazione non spesi (UTXO) sparpagliati nella blockchain. Una UTXO può avere un valore arbitrario denominato in multipli di satoshi (satoshis). Proprio come i dollari che possono essere divisi alla seconda cifra decimale come i centesimi, i bitcoin possono essere divisi fino all ottava cifra decimale come i satoshi. Anche se gli UTXO possono contenere un qualsiasi valore, quando creati questo valore è indivisibile proprio come una moneta che non può essere divisa a metà. Se un UTXO è più grande del valore desiderato della transazione, deve tuttavia essere consumato nella sua interezza e il resto deve essere generato nella transazione. In altre parole, se hai una UTXO da 20 bitcoin e vuoi pagare 1 bitcoin, la tua transazione deve consumare tutto l UTXO da 20 bitcoin e produrre due output: uno che paga 1 bitcoin al tuo destinatario desiderato e un altro che paga 19 bitcoin come resto indietro al tuo wallet. Come risultato, la maggior parte delle transazioni bitcoin genereranno resto. Immagina un cliente che compra una bevanda da 1.50$, prendendo il suo wallet e provando a trovare una combinazione di monete e banconote per coprire il costo da 1.50$. Il cliente sceglierà l esatto resto se disponibile (una banconota da un dollaro e due da 25 cent), o una combinazione di denominazioni più piccole (sei monete da 25cent), o se necessario, una unità piu grande quale una banconota da cinque dollari. Se lei da troppa moneta, come per esempio 5$, al proprietario del negozio, lei si aspetterà di ricevere 3.50$ di resto, i quali ritorneranno al suo wallet e in questo modo lei li avrà disponibili per transazioni future. Nello stesso modo, una transazione bitcoin deve essere creata da una UTXO di un utente in qualsiasi denominazioni questo utente abbia a disposizione. Gli utenti non possono tagliare una UTXO a metà più che possono tagliare una banconota da un dollaro a metà e utilizzarla come moneta. L applicazione wallet dell utente selezionerà solitamente dagli UTXO disponibili da parte dell utente varie unità per comporre una somma più grande o uguale del valore di transazione desiderato. Come nella vita reale, l applicazione bitcoin può usare diverse strategie per soddisfare la somma da trasferire (in questo caso l acquisto): combinando diverse unità più piccole, trovando il resto giusto, o usando una singola unità più grande del valore della transazione e creare il resto. Tutto questo 4

119 complesso assemblaggio di UTXO spendibili è fatto dal wallet dell utente automaticamente ed è invisibile agli utenti. E' solo rilevante se stai costruendo programmaticamente transazioni raw da UTXO. Le UTXO consumate da una transazione sono chiamati input della transazione (transaction input), e le UTXO create da una transazione sono chiamati output della transazione (transaction output). In questo modo, una parte di valore bitcoin si muove in avanti da un proprietario all altro in una catena di transazioni che consumano e creano UTXO. Le transazioni consumano UTXO sbloccandola con la firma del proprietario attuale e creano UTXO bloccandola sull indirizzo bitcoin di un nuovo proprietario. L eccezione alla catena di output e input è un tipo speciale di transazione chiamata la transazione coinbase, che è la prima transazione in ogni blocco. Questa transazione è immessa li (nella blockchain) dal miner "vincitore" e crea bitcoin "nuovi-di-zecca" pagabili a quel miner come ricompensa per aver effettuato il lavoro di mining. Questo è il modo (e l unico modo, ndt.) in cui la massa monetaria (money supply) di bitcoin è creata durante il processo di mining, come vedremo nel [ch8]. TIP Cosa viene per primo? Gli input o gli output, l uovo o la gallina? Tecnicamente, gli output vengono prima a causa delle transazioni coinbase, le quali generano nuovi bitcoin, esse non hanno input e creano output dal niente. Output della Transazione Ogni transazione bitcoin crea output, che sono registrati sul registro di bitcoin (ledger). Quasi tutti questi output, con una eccezzione (vedi Data Output (OP_RETURN)) creano pezzi spendibili di bitcoin chiamati unspent transaction outputs o UTXO (output di transazione non spesi), i quali sono poi riconosciuti da tutto il network e disponibili per il proprietario per spenderli in una futura transazioni. Inviando a qualcuno bitcoin è l azione del creare un output di una transazione unspent (non spesa), cioè un UTXO, registrata con all interno il loro indirizzo di modo che sia disponibile per loro spenderli. Gli UTXO sono tracciati da ogni client bitcoin full-node come serie di dati chiamati la UTXO set o UTXO pool, salvata in un database. Le nuove transazioni consumano (spendono) uno o più di questi output dal set di UTXO. Gli output di una Transazione consistono di due parti: Un importo di bitcoin, denominati in satoshi, l unità più piccola di bitcoin A locking script, noto anche come "ingombro" che "blocca" questo importo specificando le condizioni che devono essere soddisfatte per passare l uscita Il linguaggio di scripting delle transazioni, usato nel locking script menzionato precedentemente, è discusso in dettaglio in Script di Transazione e Linguaggio Bitcoin Script. La struttura di un output di una transazione invece mostra la struttura dell output di una transazione. Table 2. La struttura di un output di una transazione 5

120 Dimensione Campo Descrizione 8 bytes Importo Valore bitcoin rappresentato in satoshi (10-8 bitcoin) 1-9 byte (VarInt) Dimensione del Locking-Script Lunghezza del Locking-Script in byte, a seguire Variable Script di Locking Uno script che definisce le condizioni necessarie per spendere l output In Uno script che chiama l API di blockchain.info per trovare gli UTXO relativi ad un indirizzo, usiamo l API di blockchain.info per trovare gli unspent output (UTXO) di un indirizzo specifico. Example 1. Uno script che chiama l API di blockchain.info per trovare gli UTXO relativi ad un indirizzo # get unspent outputs from blockchain API import json import requests # example address address = '1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX' # The API URL is # It returns a JSON object with a list "unspent_outputs", containing UTXO, like this: #{ "unspent_outputs":[ # { # "tx_hash":"ebadfaa92f1fd29e2fe296eda702c48bd11ffd52313e986e99ddad ", # "tx_index": , # "tx_output_n": 1, # "script":"76a9148c7e252f8d64b0b6e fcfefcf4a2d88ac", # "value": , # "value_hex": "7a1200", # "confirmations":28691 # }, #... #]} resp = requests.get(' % address) utxo_set = json.loads(resp.text)["unspent_outputs"] for utxo in utxo_set: print "%s:%d - %ld Satoshis" % (utxo['tx_hash'], utxo['tx_output_n'], utxo['value']) 6

121 Eseguendo lo script, possiamo notare una lista di transaction ID, il carattere due punti, il numero dell indice di un unspent transaction output (UTXO) specifico, e il valore di quell UTXO in satoshi. Il locking script non è mostrato nell output in Eseguendo lo script get-utxo.py. Example 2. Eseguendo lo script get-utxo.py $ python get-utxo.py ebadfaa92f1fd29e2fe296eda702c48bd11ffd52313e986e99ddad : Satoshis 6596fd070679de96e405d52b51b8e1d ec4cbfe a1ecf: Satoshis 74d788804e2aae10891d72753d1520da1206e6f4f20481cc1555b7f2cb44aca0: Satoshis b2affea89ff82557c60d635a2a3137b8f88f12ecec85082f7d0a1f82ee203ac4: Satoshis... Le condizioni per lo Spending (oneri) Transaction outputs associate a specific amount (in satoshis) to a specific encumbrance or locking script that defines the condition that must be met to spend that amount. In most cases, the locking script will lock the output to a specific bitcoin address, thereby transferring ownership of that amount to the new owner. When Alice paid Bob s Cafe for a cup of coffee, her transaction created a bitcoin output encumbered or locked to the cafe s bitcoin address. That bitcoin output was recorded on the blockchain and became part of the Unspent Transaction Output set, meaning it showed in Bob s wallet as part of the available balance. When Bob chooses to spend that amount, his transaction will release the encumbrance, unlocking the output by providing an unlocking script containing a signature from Bob s private key. Input della Transaction In simple terms, transaction inputs are pointers to UTXO. They point to a specific UTXO by reference to the transaction hash and sequence number where the UTXO is recorded in the blockchain. To spend UTXO, a transaction input also includes unlocking scripts that satisfy the spending conditions set by the UTXO. The unlocking script is usually a signature proving ownership of the bitcoin address that is in the locking script. When users make a payment, their wallet constructs a transaction by selecting from the available UTXO. For example, to make a bitcoin payment, the wallet app may select a 0.01 UTXO and a UTXO, using them both to add up to the desired payment amount. In Uno script per calcolare quanti bitcoin totali saranno emessi, we show the use of a "greedy" algorithm to select from available UTXO in order to make a specific payment amount. In the example, the available UTXO are provided as a constant array, but in reality, the available UTXO would be retrieved with an RPC call to Bitcoin Core, or to a third-party API as shown in Uno script che chiama l API di blockchain.info per trovare gli UTXO relativi ad un indirizzo. 7

122 Example 3. Uno script per calcolare quanti bitcoin totali saranno emessi # Selects outputs from a UTXO list using a greedy algorithm. from sys import argv class OutputInfo: def init (self, tx_hash, tx_index, value): self.tx_hash = tx_hash self.tx_index = tx_index self.value = value def repr (self): return "<%s:%s with %s Satoshis>" % (self.tx_hash, self.tx_index, self.value) # Select optimal outputs for a send from unspent outputs list. # Returns output list and remaining change to be sent to # a change address. def select_outputs_greedy(unspent, min_value): # Fail if empty. if not unspent: return None # Partition into 2 lists. lessers = [utxo for utxo in unspent if utxo.value < min_value] greaters = [utxo for utxo in unspent if utxo.value >= min_value] key_func = lambda utxo: utxo.value if greaters: # Not-empty. Find the smallest greater. min_greater = min(greaters) change = min_greater.value - min_value return [min_greater], change # Not found in greaters. Try several lessers instead. # Rearrange them from biggest to smallest. We want to use the least # amount of inputs as possible. lessers.sort(key=key_func, reverse=true) result = [] accum = 0 for utxo in lessers: result.append(utxo) accum += utxo.value if accum >= min_value: change = accum - min_value return result, "Change: %d Satoshis" % change # No results found. return None, 0 8

123 def main(): unspent = [ OutputInfo("ebadfaa92f1fd29e2fe296eda702c48bd11ffd52313e986e99ddad ", 1, ), OutputInfo("6596fd070679de96e405d52b51b8e1d ec4cbfe a1ecf", 0, ), OutputInfo("b2affea89ff82557c60d635a2a3137b8f88f12ecec85082f7d0a1f82ee203ac4", 0, ), OutputInfo("7dbc497969c7475e45d952c4a872e213fb15d45e5cd3473c386a71a1b0c136a1", 0, ), OutputInfo("55ea01bd7e9afd3d3ab e777d62a0709cf0725e80a7350fdb22d7b8ec6", 17, ), OutputInfo("12b6a7934c1df821945ee9ee3b3326d07ca7a65fd6416ea44ce8c3db0c078c64", 0, ), OutputInfo("7f42eda67921ee92eae5f79bd37c68c9cb859b899ce70dba68c b7818", 0, ), ] if len(argv) > 1: target = long(argv[1]) else: target = print "For transaction amount %d Satoshis (%f bitcoin) use: " % (target, target/10.0**8) print select_outputs_greedy(unspent, target) if name == " main ": main() If we run the select-utxo.py script without a parameter, it will attempt to construct a set of UTXO (and change) for a payment of 55,000,000 satoshis (0.55 bitcoin). If you provide a target payment amount as a parameter, the script will select UTXO to make that target payment amount. In Lanciando lo script select-utxo.py, we run the script trying to make a payment of 0.5 bitcoin or 50,000,000 satoshis. 9

124 Example 4. Lanciando lo script select-utxo.py $ python select-utxo.py Per una transazione con valore di Satoshi ( bitcoin) usa: ([<7dbc497969c7475e45d952c4a872e213fb15d45e5cd3473c386a71a1b0c136a1:0 with Satoshis>, <7f42eda67921ee92eae5f79bd37c68c9cb859b899ce70dba68c b7818:0 with Satoshis>, <6596fd070679de96e405d52b51b8e1d ec4cbfe a1ecf:0 with Satoshis>], 'Change: Satoshis') Once the UTXO is selected, the wallet then produces unlocking scripts containing signatures for each of the UTXO, thereby making them spendable by satisfying their locking script conditions. The wallet adds these UTXO references and unlocking scripts as inputs to the transaction. La struttura di un input di una transazione shows the structure of a transaction input. Table 3. La struttura di un input di una transazione Dimensione Campo Descrizione 32 bytes Hash della Transazione Puntatore alla transazione contenente l UTXO che andrà speso 4 bytes Indice dell Output Il numero indice dell UTXO speso; il primo è bytes (VarInt) Dimensione dell Unlocking- Script Lunghezza dell Unlocking-Script in bytes, a seguire Variable Unlocking-Script Uno script che completa le condizioni del locking script dell UTXO. 4 bytes Sequence Number Attualmente disabilitato, funzione di Tx-replacement, impostato a 0xFFFFFFFF NOTE Il numero della sequenza è usato per sovrascrivere una transazione prima della scadenza del locktime della transazione, che è una funzione attualmente disabilitata in bitcoin. La maggior parte delle transazioni impostano questo valore al massimo valore intero (0xFFFFFFFF) così che sia ignorato dal network bitcoin. Se la transazione ha un locktime diverso da zero, almeno uno dei suoi input deve avere un numero di sequenza inferiore a 0xFFFFFFFF per abilitare il locktime. Commissioni sulla Transazione (transaction fee) Most transactions include transaction fees, which compensate the bitcoin miners for securing the 10

125 network. Mining and the fees and rewards collected by miners are discussed in more detail in [ch8]. This section examines how transaction fees are included in a typical transaction. Most wallets calculate and include transaction fees automatically. However, if you are constructing transactions programmatically, or using a command-line interface, you must manually account for and include these fees. Transaction fees serve as an incentive to include (mine) a transaction into the next block and also as a disincentive against "spam" transactions or any kind of abuse of the system, by imposing a small cost on every transaction. Transaction fees are collected by the miner who mines the block that records the transaction on the blockchain. Transaction fees are calculated based on the size of the transaction in kilobytes, not the value of the transaction in bitcoin. Overall, transaction fees are set based on market forces within the bitcoin network. Miners prioritize transactions based on many different criteria, including fees, and might even process transactions for free under certain circumstances. Transaction fees affect the processing priority, meaning that a transaction with sufficient fees is likely to be included in the next-most mined block, whereas a transaction with insufficient or no fees might be delayed, processed on a best-effort basis after a few blocks, or not processed at all. Transaction fees are not mandatory, and transactions without fees might be processed eventually; however, including transaction fees encourages priority processing. Over time, the way transaction fees are calculated and the effect they have on transaction prioritization has been evolving. At first, transaction fees were fixed and constant across the network. Gradually, the fee structure has been relaxed so that it may be influenced by market forces, based on network capacity and transaction volume. The current minimum transaction fee is fixed at bitcoin or a tenth of a milli-bitcoin per kilobyte, recently decreased from one milli-bitcoin. Most transactions are less than one kilobyte; however, those with multiple inputs or outputs can be larger. In future revisions of the bitcoin protocol, it is expected that wallet applications will use statistical analysis to calculate the most appropriate fee to attach to a transaction based on the average fees of recent transactions. L algoritmo usato attualmente dai miner per prioritizzare le transazioni per l inclusione in un blocco basato sulle rispettive fee è esaminato in dettaglio in [ch8]. Impostare le Commissioni sulle Transazioni The data structure of transactions does not have a field for fees. Instead, fees are implied as the difference between the sum of inputs and the sum of outputs. Any excess amount that remains after all outputs have been deducted from all inputs is the fee that is collected by the miners. Le transaction fee sono l eccesso degli input meno gli output: Fees = Sum(Inputs) Sum(Outputs) This is a somewhat confusing element of transactions and an important point to understand, because if 11

126 you are constructing your own transactions you must ensure you do not inadvertently include a very large fee by underspending the inputs. That means that you must account for all inputs, if necessary by creating change, or you will end up giving the miners a very big tip! For example, if you consume a 20-bitcoin UTXO to make a 1-bitcoin payment, you must include a 19- bitcoin change output back to your wallet. Otherwise, the 19-bitcoin "leftover" will be counted as a transaction fee and will be collected by the miner who mines your transaction in a block. Although you will receive priority processing and make a miner very happy, this is probably not what you intended. Se dimentichi di aggiungere un output a cui inviare il resto in una transazione costruita manualmente, il resto verrà attribuito come transaction fee. "Tieni il resto!" non è sempre quello che intendevi. Vediamo come funziona in pratica, osservando nuovamente l acquisto del caffè effettuato da Alice. Alice vuole spendere bitcoin per pagare il caffè. Per assicurare che questa transazione sia processata rapidamente, Alice vorrà includere una fee di transazione, diciamo Questo vorrà dire che il costo totale della transazione sarà di bitcoin. Il suo wallet dovrà quindi recuperare una serie di UTXO che arrivi a o più e, se necessario, emettere il resto. Diciamo che il suo wallet abbia 0.2 bitcoin disponibili nelle UTXO. Dovrà quindi consumare queste UTXO, creare un output verso il Caffè di Bob da 0.015, e un secondo output con bitcoin come resto re-inviati indietro al proprio wallet, lasciando bitcoin non allocati, come fee implicita per la transazione. Ora diamo un occhiata ad uno scenario differente. Eugenia, la nostra direttrice dell organizzazione no profit nelle Filippine, ha completato una campagna di raccolta fondi per comprare libri di scuola per i bambini. Ha ricevuto molte piccole donazioni provenienti da persone in tutto il mondo, totalizzando 50 bitcoin, quindi il suo wallet è pieno di molti pagamenti molto piccoli (UTXO). A questo punto Eugenia vuole acquistare centinaia di libri di scuola da un editore locale. Come l applicazione wallet di Eugenia prova a costruire una transazione singola per il pagamento, deve recuperare dalla serie di UTXO disponibili, che sono composte da varie transazioni più piccole. Questo vuol dire che la transazione risultante recupererà da più di un centinaio di UTXO di poco valore per quanto riguarda l input e emetterà un solo output, pagando l editore del libro. Una transazione con così tanti input sarà più grande di un kilobyte, forse dai 2 ai 3 kilobytes di dimensione. Come risultato, richiederà una fee più alta della network fee minima di bitcoin. L applicazione wallet di Eugenia calcolerà le fee appropriate misurando la dimensione della transazione e moltiplicandola per la fee per kilobyte. Molti wallet pagano un valore di fee più alto per transazioni di dimensione maggiore per assicurarsi che la transazione sia eseguita rapidamente. Si ottiene una fee maggiorata non perchè Eugenia sta spendendo più soldi, invece è perchè la sua transazione è piu complessa e di più grande dimensione la fee è indipendente rispetto al valore in bitcoin della transazione. 12

127 Collegare Transazioni e Transazioni Orfane As we have seen, transactions form a chain, whereby one transaction spends the outputs of the previous transaction (known as the parent) and creates outputs for a subsequent transaction (known as the child). Sometimes an entire chain of transactions depending on each other say a parent, child, and grandchild transaction are created at the same time, to fulfill a complex transactional workflow that requires valid children to be signed before the parent is signed. For example, this is a technique used in CoinJoin transactions where multiple parties join transactions together to protect their privacy. When a chain of transactions is transmitted across the network, they don t always arrive in the same order. Sometimes, the child might arrive before the parent. In that case, the nodes that see a child first can see that it references a parent transaction that is not yet known. Rather than reject the child, they put it in a temporary pool to await the arrival of its parent and propagate it to every other node. The pool of transactions without parents is known as the orphan transaction pool. Once the parent arrives, any orphans that reference the UTXO created by the parent are released from the pool, revalidated recursively, and then the entire chain of transactions can be included in the transaction pool, ready to be mined in a block. Transaction chains can be arbitrarily long, with any number of generations transmitted simultaneously. The mechanism of holding orphans in the orphan pool ensures that otherwise valid transactions will not be rejected just because their parent has been delayed and that eventually the chain they belong to is reconstructed in the correct order, regardless of the order of arrival. There is a limit to the number of orphan transactions stored in memory, to prevent a denial-of-service attack against bitcoin nodes. The limit is defined as MAX_ORPHAN_TRANSACTIONS in the source code of the bitcoin reference client. If the number of orphan transactions in the pool exceeds MAX_ORPHAN_TRANSACTIONS, one or more randomly selected orphan transactions are evicted from the pool, until the pool size is back within limits. Script di Transazione e Linguaggio Bitcoin Script Bitcoin clients validate transactions by executing a script, written in a Forth-like scripting language. Both the locking script (encumbrance) placed on a UTXO and the unlocking script that usually contains a signature are written in this scripting language. When a transaction is validated, the unlocking script in each input is executed alongside the corresponding locking script to see if it satisfies the spending condition. Oggi, la maggior parte delle transazioni processate attraverso il network bitcoin hanno la forma "Alice paga Bob" e sono basate sullo stesso script chiamato script Pay-to-Public-Key-Hash. Tuttavia, l uso di script per fare il lock degli output e aggiungere regole di input che possano rimuovere il lock significa che attraverso l uso del linguaggio di programmazione, le transazioni possono contenere un numero infinito di condizioni. Le transazioni bitcoin non sono limitate nella forma e nello schema di "Alice paga Bob". Questa è solo la punta dell iceberg delle possibilità che possono essere espresse con questo linguaggio di scripting. In questa sezione, dimostreremo che i componenti del linguaggio bitcoin scripting delle 13

128 transazioni e mostreremo come può essere utilizzato per esprimere condizioni complesse per lo spending dei bitcoin e come queste condizioni possono essere soddisfatte da vari unlocking script. TIP La validazione delle transazioni bitcoin non è basata su di uno schema statico, ma invece è ottenuta tramite l esecuzione di un linguaggio di scripting. Questo linguaggio permette di esprimere una quasi infinita varietà di condizioni. E' questo il modo nel cui bitcoin ottiene la potenza di "valuta programmabile" (programmable money). Costruzione dello Script (Lock + Unlock) Il motore di validazione di transazioni bitcoin fa affidamento su due tipi di script per validare le transazioni: un locking script e uno script di unlock. A locking script is an encumbrance placed on an output, and it specifies the conditions that must be met to spend the output in the future. Historically, the locking script was called a scriptpubkey, because it usually contained a public key or bitcoin address. In this book we refer to it as a "locking script" to acknowledge the much broader range of possibilities of this scripting technology. In most bitcoin applications, what we refer to as a locking script will appear in the source code as scriptpubkey. An unlocking script is a script that "solves," or satisfies, the conditions placed on an output by a locking script and allows the output to be spent. Unlocking scripts are part of every transaction input, and most of the time they contain a digital signature produced by the user s wallet from his or her private key. Historically, the unlocking script is called scriptsig, because it usually contained a digital signature. In most bitcoin applications, the source code refers to the unlocking script as scriptsig. In this book, we refer to it as an "unlocking script" to acknowledge the much broader range of locking script requirements, because not all unlocking scripts must contain signatures. Every bitcoin client will validate transactions by executing the locking and unlocking scripts together. For each input in the transaction, the validation software will first retrieve the UTXO referenced by the input. That UTXO contains a locking script defining the conditions required to spend it. The validation software will then take the unlocking script contained in the input that is attempting to spend this UTXO and execute the two scripts. In the original bitcoin client, the unlocking and locking scripts were concatenated and executed in sequence. For security reasons, this was changed in 2010, because of a vulnerability that allowed a malformed unlocking script to push data onto the stack and corrupt the locking script. In the current implementation, the scripts are executed separately with the stack transferred between the two executions, as described next. First, the unlocking script is executed, using the stack execution engine. If the unlocking script executed without errors (e.g., it has no "dangling" operators left over), the main stack (not the alternate stack) is copied and the locking script is executed. If the result of executing the locking script with the stack data copied from the unlocking script is "TRUE," the unlocking script has succeeded in resolving the conditions imposed by the locking script and, therefore, the input is a valid authorization to spend the UTXO. If any result other than "TRUE" remains after execution of the combined script, the input is invalid because it has failed to satisfy the spending conditions placed on the UTXO. Note that the UTXO 14

129 is permanently recorded in the blockchain, and therefore is invariable and is unaffected by failed attempts to spend it by reference in a new transaction. Only a valid transaction that correctly satisfies the conditions of the UTXO results in the UTXO being marked as "spent" and removed from the set of available (unspent) UTXO. Combinando scriptsig e scriptpubkey per valutare un transaction script is an example of the unlocking and locking scripts for the most common type of bitcoin transaction (a payment to a public key hash), showing the combined script resulting from the concatenation of the unlocking and locking scripts prior to script validation. Figure 1. Combinando scriptsig e scriptpubkey per valutare un transaction script Linguaggio di Scripting The bitcoin transaction script language, called Script, is a Forth-like reverse-polish notation stack-based execution language. If that sounds like gibberish, you probably haven t studied 1960 s programming languages. Script is a very simple language that was designed to be limited in scope and executable on a range of hardware, perhaps as simple as an embedded device, such as a handheld calculator. It requires minimal processing and cannot do many of the fancy things modern programming languages can do. In the case of programmable money, that is a deliberate security feature. Il linguaggio bitcoin scripting è detto un linguaggio stack-based perché utilizza una struttura dati chiamata stack. Lo stack (pila) è una struttura dati molto semplice, che può essere visualizzata come un mazzo di carte. Uno stack permette due operazioni: push e pop. Push aggiunge gli elementi in cima alla pila. Pop rimuove l elemento in cima alla pila. The scripting language executes the script by processing each item from left to right. Numbers (data constants) are pushed onto the stack. Operators push or pop one or more parameters from the stack, act on them, and might push a result onto the stack. For example, OP_ADD will pop two items from the stack, add them, and push the resulting sum onto the stack. Conditional operators evaluate a condition, producing a boolean result of TRUE or FALSE. For example, OP_EQUAL pops two items from the stack and pushes TRUE (TRUE is represented by the number 1) if they are equal or FALSE (represented by zero) if they are not equal. Bitcoin transaction scripts usually contain a conditional operator, so that they can produce the TRUE result that signifies a valid transaction. 15

130 In Validazione di un bitcoin script usando la matematica, the script 2 3 OP_ADD 5 OP_EQUAL demonstrates the arithmetic addition operator OP_ADD, adding two numbers and putting the result on the stack, followed by the conditional operator OP_EQUAL, which checks that the resulting sum is equal to 5. For brevity, the OP_ prefix is omitted in the step-by-step example. Il seguente è uno script leggermente più complesso, che calcola Nota che quando lo script contiene una serie di operatori, lo attacchi permette al risultato di un operatore di essere utilizzato dall operatore successivo: 2 7 OP_ADD 3 OP_SUB 1 OP_ADD 7 OP_EQUAL Prova a validare il precedente script tu stesso usando carta e penna. Quando l esecuzione dello script finisce, rimarrà il valore TRUE nello stack. Although most locking scripts refer to a bitcoin address or public key, thereby requiring proof of ownership to spend the funds, the script does not have to be that complex. Any combination of locking and unlocking scripts that results in a TRUE value is valid. The simple arithmetic we used as an example of the scripting language is also a valid locking script that can be used to lock a transaction output. Usa una parte dello script aritmetico di esempio come locking script: 3 OP_ADD 5 OP_EQUAL che può essere soddisfatta da una transazione che contiene un input con lo script di unlocking: 2 Il software di validazione combina gli script di locking e unlocking e lo script risultante è: 2 3 OP_ADD 5 OP_EQUAL As we saw in the step-by-step example in Validazione di un bitcoin script usando la matematica, when this script is executed, the result is OP_TRUE, making the transaction valid. Not only is this a valid transaction output locking script, but the resulting UTXO could be spent by anyone with the arithmetic skills to know that the number 2 satisfies the script. 16

131 17

132 Figure 2. Validazione di un bitcoin script usando la matematica TIP Transactions are valid if the top result on the stack is TRUE (noted as {0x01}), any other non-zero value or if the stack is empty after script execution. Transactions are invalid if the top value on the stack is FALSE (a zero-length empty value, noted as {}) or if script execution is halted explicitly by an operator, such as OP_VERIFY, OP_RETURN, or a conditional terminator such as OP_ENDIF. See [tx_script_ops] for details. Incompletezza di Turing The bitcoin transaction script language contains many operators, but is deliberately limited in one important way there are no loops or complex flow control capabilities other than conditional flow control. This ensures that the language is not Turing Complete, meaning that scripts have limited complexity and predictable execution times. Script is not a general-purpose language. These limitations ensure that the language cannot be used to create an infinite loop or other form of "logic bomb" that could be embedded in a transaction in a way that causes a denial-of-service attack against the bitcoin network. Remember, every transaction is validated by every full node on the bitcoin network. A limited language prevents the transaction validation mechanism from being used as a vulnerability. Stateless Verification The bitcoin transaction script language is stateless, in that there is no state prior to execution of the script, or state saved after execution of the script. Therefore, all the information needed to execute a script is contained within the script. A script will predictably execute the same way on any system. If your system verifies a script, you can be sure that every other system in the bitcoin network will also verify the script, meaning that a valid transaction is valid for everyone and everyone knows this. This predictability of outcomes is an essential benefit of the bitcoin system. Transazioni Standard In the first few years of bitcoin s development, the developers introduced some limitations in the types of scripts that could be processed by the reference client. These limitations are encoded in a function called isstandard(), which defines five types of "standard" transactions. These limitations are temporary and might be lifted by the time you read this. Until then, the five standard types of transaction scripts are the only ones that will be accepted by the reference client and most miners who run the reference client. Although it is possible to create a nonstandard transaction containing a script that is not one of the standard types, you must find a miner who does not follow these limitations to mine that transaction into a block. Controlla il codice sorgente del client Bitcoin Core (l implementazione di riferimento) per controllare cos è attualmente consentito come script di transazione valido. The five standard types of transaction scripts are pay-to-public-key-hash (P2PKH), public-key, multi- 18

133 signature (limited to 15 keys), pay-to-script-hash (P2SH), and data output (OP_RETURN), which are described in more detail in the following sections. Pay-to-Public-Key-Hash (P2PKH) The vast majority of transactions processed on the bitcoin network are P2PKH transactions. These contain a locking script that encumbers the output with a public key hash, more commonly known as a bitcoin address. Transactions that pay a bitcoin address contain P2PKH scripts. An output locked by a P2PKH script can be unlocked (spent) by presenting a public key and a digital signature created by the corresponding private key. For example, let s look at Alice s payment to Bob s Cafe again. Alice made a payment of bitcoin to the cafe s bitcoin address. That transaction output would have a locking script of the form: OP_DUP OP_HASH160 <Cafe Public Key Hash> OP_EQUAL OP_CHECKSIG The Cafe Public Key Hash is equivalent to the bitcoin address of the cafe, without the Base58Check encoding. Most applications would show the public key hash in hexadecimal encoding and not the familiar bitcoin address Base58Check format that begins with a "1". Il locking script precedente può essere soddisfatto dall unlocking script nella forma: <Cafe Signature> <Cafe Public Key> I due script insieme andrebbero a formare il seguente script di validazione combinato: <Cafe Signature> <Cafe Public Key> OP_DUP OP_HASH160 <Cafe Public Key Hash> OP_EQUAL OP_CHECKSIG When executed, this combined script will evaluate to TRUE if, and only if, the unlocking script matches the conditions set by the locking script. In other words, the result will be TRUE if the unlocking script has a valid signature from the cafe s private key that corresponds to the public key hash set as an encumbrance. Figures <xref linkend="p2pubkhash1" xrefstyle="select: labelnumber"/> and <xref linkend="p2pubkhash2" xrefstyle="select: labelnumber"/> show (in two parts) a step-by-step execution of the combined script, which will prove this is a valid transaction. 19

134 Figure 3. Valutando uno script per una transazione P2PKH (Parte 1 di 2) Pay-to-Public-Key Pay-to-public-key is a simpler form of a bitcoin payment than pay-to-public-key-hash. With this script form, the public key itself is stored in the locking script, rather than a public-key-hash as with P2PKH earlier, which is much shorter. Pay-to-public-key-hash was invented by Satoshi to make bitcoin addresses shorter, for ease of use. Pay-to-public-key is now most often seen in coinbase transactions, generated by older mining software that has not been updated to use P2PKH. Uno script di locking pay-to-public-key è simile al seguente esempio: <Public Key A> OP_CHECKSIG L unlocking script corrispondente che deve essere presentato per sbloccare questo tipo di output è una 20

135 semplice firma, come questa: <Signature from Private Key A> Lo script combinato, che è validato dal software di validazione della transazione, è: <Signature from Private Key A> <Public Key A> OP_CHECKSIG Questo script è una semplice chiamata all operatore CHECKSIG, che valida la firma affinchè corrisponda alla chiave corretta e ritorni TRUE sullo stack. 21

136 Figure 4. Eseguendo uno script per una transazione P2PKH (Parte 2 di 2) Multi-Firma (Multi-Signature) Multi-signature scripts set a condition where N public keys are recorded in the script and at least M of those must provide signatures to release the encumbrance. This is also known as an M-of-N scheme, where N is the total number of keys and M is the threshold of signatures required for validation. For example, a 2-of-3 multi-signature is one where three public keys are listed as potential signers and at least two of those must be used to create signatures for a valid transaction to spend the funds. At this time, standard multi-signature scripts are limited to at most 15 listed public keys, meaning you can do 22

137 anything from a 1-of-1 to a 15-of-15 multi-signature or any combination within that range. The limitation to 15 listed keys might be lifted by the time this book is published, so check the isstandard() function to see what is currently accepted by the network. La forma generale di uno script di locking che imposta una condizione multi signature M-di-N è: M <Public Key 1> <Public Key 2>... <Public Key N> N OP_CHECKMULTISIG dove N è il numero totale di chiavi pubbliche elencate e M è la soglia del numero di firme richiesto per spendere un output. Uno script di locking che imposta una condizione multi-signnature-2-su-3 assomiglia a questo: 2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG Il locking script precedente può essere soddisfatto con un unlocking script contenente coppie di firme e chiavi pubbliche: OP_0 <Signature B> <Signature C> o una qualsiasi combinazione di due firme dalle chiavi private corrispondenti alle tre chiavi pubbliche elencate. NOTE The prefix OP_0 is required because of a bug in the original implementation of CHECKMULTISIG where one item too many is popped off the stack. It is ignored by CHECKMULTISIG and is simply a placeholder. I due script insieme formeranno uno script di validazione combinato: OP_0 <Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG Quando eseguito, questo script combinato ritornerà TRUE se, e solo se, lo script di unlock pareggia le condizioni impostate dallo script di lock. In questo caso, la condizione è dove lo script di unlock ha una firma valida dalle due chiavi private che corrispondono a due delle tre chiavi pubbliche impostate come impaccio (encumberance). Data Output (OP_RETURN) Bitcoin s distributed and timestamped ledger, the blockchain, has potential uses far beyond payments. Many developers have tried to use the transaction scripting language to take advantage of the security and resilience of the system for applications such as digital notary services, stock certificates, and 23

138 smart contracts. Early attempts to use bitcoin s script language for these purposes involved creating transaction outputs that recorded data on the blockchain; for example, to record a digital fingerprint of a file in such a way that anyone could establish proof-of-existence of that file on a specific date by reference to that transaction. The use of bitcoin s blockchain to store data unrelated to bitcoin payments is a controversial subject. Many developers consider such use abusive and want to discourage it. Others view it as a demonstration of the powerful capabilities of blockchain technology and want to encourage such experimentation. Those who object to the inclusion of non-payment data argue that it causes "blockchain bloat," burdening those running full bitcoin nodes with carrying the cost of disk storage for data that the blockchain was not intended to carry. Moreover, such transactions create UTXO that cannot be spent, using the destination bitcoin address as a free-form 20-byte field. Because the address is used for data, it doesn t correspond to a private key and the resulting UTXO can never be spent; it s a fake payment. These transactions that can never be spent are therefore never removed from the UTXO set and cause the size of the UTXO database to forever increase, or "bloat." In version 0.9 of the Bitcoin Core client, a compromise was reached with the introduction of the OP_RETURN operator. OP_RETURN allows developers to add 80 bytes of nonpayment data to a transaction output. However, unlike the use of "fake" UTXO, the OP_RETURN operator creates an explicitly provably unspendable output, which does not need to be stored in the UTXO set. OP_RETURN outputs are recorded on the blockchain, so they consume disk space and contribute to the increase in the blockchain s size, but they are not stored in the UTXO set and therefore do not bloat the UTXO memory pool and burden full nodes with the cost of more expensive RAM. gli script OP_RETURN sono fatti così: OP_RETURN <data> The data portion is limited to 80 bytes and most often represents a hash, such as the output from the SHA256 algorithm (32 bytes). Many applications put a prefix in front of the data to help identify the application. For example, the Proof of Existence digital notarization service uses the 8-byte prefix "DOCPROOF," which is ASCII encoded as 44f f4f46 in hexadecimal. Keep in mind that there is no "unlocking script" that corresponds to OP_RETURN that could possibly be used to "spend" an OP_RETURN output. The whole point of OP_RETURN is that you can t spend the money locked in that output, and therefore it does not need to be held in the UTXO set as potentially spendable OP_RETURN is provably un-spendable. OP_RETURN is usually an output with a zero bitcoin amount, because any bitcoin assigned to such an output is effectively lost forever. If an OP_RETURN is encountered by the script validation software, it results immediately in halting the execution of the validation script and marking the transaction as invalid. Thus, if you accidentally reference an OP_RETURN output as an input in a transaction, that transaction is invalid. A standard transaction (one that conforms to the isstandard() checks) can have only one OP_RETURN output. However, a single OP_RETURN output can be combined in a transaction with outputs of any other type. 24

139 Two new command-line options have been added in Bitcoin Core as of version The option datacarrier controls relay and mining of OP_RETURN transactions, with the default set to "1" to allow them. The option datacarriersize takes a numeric argument specifying the maximum size in bytes of the OP_RETURN data, 40 bytes by default. NOTE OP_RETURN was initially proposed with a limit of 80 bytes, but the limit was reduced to 40 bytes when the feature was released. In February 2015, in version 0.10 of Bitcoin Core, the limit was raised back to 80 bytes. Nodes may choose not to relay or mine OP_RETURN, or only relay and mine OP_RETURN containing less than 80 bytes of data. Pay-to-Script-Hash (P2SH) Pay-to-script-hash (P2SH) was introduced in 2012 as a powerful new type of transaction that greatly simplifies the use of complex transaction scripts. To explain the need for P2SH, let s look at a practical example. In [ch01_intro_what_is_bitcoin] we introduced Mohammed, an electronics importer based in Dubai. Mohammed s company uses bitcoin s multi-signature feature extensively for its corporate accounts. Multi-signature scripts are one of the most common uses of bitcoin s advanced scripting capabilities and are a very powerful feature. Mohammed s company uses a multi-signature script for all customer payments, known in accounting terms as "accounts receivable," or AR. With the multi-signature scheme, any payments made by customers are locked in such a way that they require at least two signatures to release, from Mohammed and one of his partners or from his attorney who has a backup key. A multi-signature scheme like that offers corporate governance controls and protects against theft, embezzlement, or loss. Lo script risultante è abbastanza lungo ed è simile a questo: 2 <Mohammed's Public Key> <Partner1 Public Key> <Partner2 Public Key> <Partner3 Public Key> <Attorney Public Key> 5 OP_CHECKMULTISIG - ( 2 <Chiave Pubblica di Mohamed> <Chiave Pubblica Partner1> <Chiave Pubblica Partner 2> <Chiave Pubblica Partner3> <Chiave Pubblica del Rappresentante Legale> 5 OP_CHECKMULTISIG ) Anche se gli script multi-signature sono una funzionalità potente, sono un po difficili da usare. Dato lo script precedente, Mohammed dovrebbe comunicare lo script a ogni cliente prima di iniziare un pagamento. Ogni cliente avrebbe dovuto usare un wallet bitcoin specifico con l abilità di creare script di transazione custom e ogni cliente avrebbe dovuto capire come creare una transazione con script custom (personalizzati). Inoltre, la transazione risultante sarà cinque volte più grande di una transazione con un semplice pagamento, perchè questo script contiene chiavi pubbliche molto lunghe. Il peso di queste transazioni extra-large andrà a gravare sull utente sotto forma di fee. Finalmente uno script così grande dovrà essere trasferito nel set delle UTXO in RAM in ogni full node, fino a che non sarà speso. Tutte queste problematiche fanno sì che l uso di output script complessi sarà un po meno pratico. 25

140 Pay-to-script-hash (P2SH) was developed to resolve these practical difficulties and to make the use of complex scripts as easy as a payment to a bitcoin address. With P2SH payments, the complex locking script is replaced with its digital fingerprint, a cryptographic hash. When a transaction attempting to spend the UTXO is presented later, it must contain the script that matches the hash, in addition to the unlocking script. In simple terms, P2SH means "pay to a script matching this hash, a script that will be presented later when this output is spent." In P2SH transactions, the locking script that is replaced by a hash is referred to as the redeem script because it is presented to the system at redemption time rather than as a locking script. Script complessi senza P2SH shows the script without P2SH and Complex script come P2SH shows the same script encoded with P2SH. Table 4. Script complessi senza P2SH Locking Script 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG Unlocking Script Sig1 Sig2 Table 5. Complex script come P2SH Script di Riscatto 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG Locking Script Unlocking Script OP_HASH160 <20-byte hash dello script di riscatto> OP_EQUAL Sig1 Sig2 dello script di riscatto As you can see from the tables, with P2SH the complex script that details the conditions for spending the output (redeem script) is not presented in the locking script. Instead, only a hash of it is in the locking script and the redeem script itself is presented later, as part of the unlocking script when the output is spent. This shifts the burden in fees and complexity from the sender to the recipient (spender) of the transaction. Osserviamo la ditta di Mohammed, lo script multi-signature complesso, e i risultanti script P2SH. Per primo, lo script multi-signature che la ditta di Mohammed usa per tutti i pagementi in entrata dai clienti: 2 <Mohammed's Public Key> <Partner1 Public Key> <Partner2 Public Key> <Partner3 Public Key> <Attorney Public Key> 5 OP_CHECKMULTISIG - ( 2 <Chiave Pubblica di Mohamed> <Chiave Pubblica Partner1> <Chiave Pubblica Partner 2> <Chiave Pubblica Partner3> <Chiave Pubblica del Rappresentante Legale> 5 OP_CHECKMULTISIG ) Se i placeholder sono rimpiazzati con chiavi pubbliche reali (mostrati qui come numeri di 520-bit che iniziano con 04) noterai che lo script diverrà molto lungo: 26

141 2 04C16B8698A9ABF84250A7C3EA7EEDEF9897D1C8C6ADF47F06CF73370D74DCCA01CDCA79DCC5C395D7EEC6984 D83F1F50C900A24DD47F569FD4193AF5DE762C58704A D8655D6A935BEAF2CA23E3FB87A3495E7AF308 EDF08DAC3C1FCBFC2C75B4B0F4D0B1B70CD C0C2B1D5CE65C97D78D0E E8B49047E632 48B75DB7379BE9CDA8CE5751D16485F431E46117B9D0C1837C9D F393DA7D4420D7E1A9162F0279CFC1 0F1E8E8F3020DECDBC3C0DD389D D65CBD7149B255382ED7F78E EE6FDA162A187543A9 D85BAAA93A4AB3A8F044DADA618D ABE8A35DA8C5B73997AD343BE5C2AFD94A AFA1E CED3C68D446BCAB69AC0BA7DF50D56231BE0AABF1FDEEC78A6A45E394BA29A1EDF518C022DD618DA774D207D1 37AAB59E0B000EB7ED238F4D800 5 OP_CHECKMULTISIG Lo script per intero può invece essere rappresentato da un hash crittografico di 20-byte, applicando in principio l algoritmo di hashing SHA256 e infine l algoritmo RIPEMD160 sul risultato. L hash di 20-byte dello script precedente è: 54c557e07dde5bb6cb791c7a540e0a4796f5e97e Una transazione P2SH blocca l output a questo hash invece dello script più lungo, usando lo script di unlock: OP_HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e OP_EQUAL che, come potete vedere, è più corto. Invece di "pagare a questo script a 5-chiavi", la transazione P2SH equivalente è "paga a uno script con questo hash." Un cliente che effettua un pagamento alla ditta di Mohammed deve includere solamente questo script di locking molto più breve nel proprio pagamento. Quando Mohammed vuole spendere questo UTXO, essi devono presentare lo script originale di riscatto (coloro che hanno protetto/firmato l UTXO) e la firma necessaria per sbloccarlo, come la seguente: <Sig1> <Sig2> <2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG> I due script sono combinati in due fasi. Nella prima, lo script di riscatto è comparato contro lo script di locking per essere sicuro che l hash combaci: <2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG> OP_HASH160 <scripthash di riscatto> OP_EQUAL Se l hash dello script di riscatto combacia, lo script di unlock è eseguito da solo, per sbloccare lo script di riscatto: <Sig1> <Sig2> 2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG 27

142 Indirizzi Pay-to-script-hash Another important part of the P2SH feature is the ability to encode a script hash as an address, as defined in BIP0013. P2SH addresses are Base58Check encodings of the 20-byte hash of a script, just like bitcoin addresses are Base58Check encodings of the 20-byte hash of a public key. P2SH addresses use the version prefix "5", which results in Base58Check-encoded addresses that start with a "3". For example, Mohammed s complex script, hashed and Base58Check-encoded as a P2SH address becomes 39RF6JqABiHdYHkfChV6USGMe6Nsr66Gzw. Now, Mohammed can give this "address" to his customers and they can use almost any bitcoin wallet to make a simple payment, as if it were a bitcoin address. The 3 prefix gives them a hint that this is a special type of address, one corresponding to a script instead of a public key, but otherwise it works in exactly the same way as a payment to a bitcoin address. Gli indirizzi P2SH nascondono tutta la complessità, di modo che la persona che effettua il pagamento non veda lo script. Benefici del pay-to-script-hash The pay-to-script-hash feature offers the following benefits compared to the direct use of complex scripts in locking outputs: Script complessi sono rimpiazzati da fingerprint più corti nell output di transazione, rendendo la transazione più piccola. Gli script possono essere codificati come un indirizzo, in questo modo il mittente e al wallet del mittente non serve un codice complesso per implementare P2SH. P2SH sposta l onere di costruzione dello script sul ricevente, non sul mittente. P2SH shifts the burden in data storage for the long script from the output (which is in the UTXO set) to the input (stored on the blockchain). P2SH shifts the burden in data storage for the long script from the present time (payment) to a future time (when it is spent). P2SH shifts the transaction fee cost of a long script from the sender to the recipient, who has to include the long redeem script to spend it. Redeem script and isstandard validation Prior to version of the Bitcoin Core client, pay-to-script-hash was limited to the standard types of bitcoin transaction scripts, by the isstandard() function. That means that the redeem script presented in the spending transaction could only be one of the standard types: P2PK, P2PKH, or multi-sig nature, excluding OP_RETURN and P2SH itself. As of version of the Bitcoin Core client, P2SH transactions can contain any valid script, making the P2SH standard much more flexible and allowing for experimentation with many novel and complex types of transactions. Note that you are not able to put a P2SH inside a P2SH redeem script, because the P2SH specification is 28

143 not recursive. You are also still not able to use OP_RETURN in a redeem script because OP_RETURN cannot be redeemed by definition. Note that because the redeem script is not presented to the network until you attempt to spend a P2SH output, if you lock an output with the hash of an invalid transaction it will be processed regardless. However, you will not be able to spend it because the spending transaction, which includes the redeem script, will not be accepted because it is an invalid script. This creates a risk, because you can lock bitcoin in a P2SH that cannot be spent later. The network will accept the P2SH encumbrance even if it corresponds to an invalid redeem script, because the script hash gives no indication of the script it represents. P2SH locking scripts contain the hash of a redeem script, which gives no clues as to the content of the redeem script itself. The P2SH transaction will be considered valid and accepted even if the redeem script is invalid. You might accidentally lock bitcoin in such a way that it cannot later be spent. 29

144 La Rete Bitcoin Architettura di Rete Peer-to-Peer Network Architecture Bitcoin è strutturato come un architettura peer-to-peer sopra internet. Il termine peer-to-peer, or P2P, sta a significare che i computer che partecipano alla rete sono (nodi n.d.t.) al pari degli altri, e sono tutti uguali, che non ci sono nodi "speciali", e che tutti i nodi condividono il compito di fornire servizi alla rete. I nodi della rete (network) sono connessi tra di loro in una rete mesh (a maglia n.d.t.) con una topologia "piatta". Non c è un server, nessun servizio centralizzato, e nessuna gerarchia di alcun tipo nella rete. I nodi in una rete peer-to-peer provvedono a fornire e utilizzano i servizi allo stesso tempo con reciprocità agendo come incentivo per la partecipazione. Le reti peer-to-peer sono resilienti per definizione, decentralizzate, e aperte. Il preminente esempio di un architettura di una rete P2P si è verificato con lo stesso internet quando era ai suoi primordi, dove i nodi della rete IP erano uguali. L architettura attuale di internet è più gerarchica, ma l Internet Protocol mantiene ancora la sua topologia-piatta che ne è l essenza. Dopo bitcoin, l applicazione più grande e con più successo delle tecnologie P2P è la condivisione dei file con Napster come suo pioniere e BitTorrent come l evoluzione più recente dell architettura. L architettura P2P di Bitcoin è molto più di una scelta tecnologica. Bitcoin è stato progettato per essere un sistema peer-to-peer di contante digitale, e l architettura del network, è sia un riflesso che le fondamenta di questa caratteristica principale. La decentralizzazione del controllo è una delle scelte architetturali principali e può essere ottenuta solamente mantenendo una rete P2P di consenso piatta (tutti i nodi hanno gli stessi privilegi) e decentralizzata. Il termine "network bitcoin" si riferisce alla serie di nodi che eseguono il protocollo P2P bitcoin. Oltre al protocollo P2P di bitcoin, ci sono altri protocolli come quello di Stratum, che sono utilizzati per il mining e per wallet bitcoin mobile o leggeri. Questi protocolli addizionali sono forniti da server gateways di routing che hanno accesso alla rete bitcoin usando il protocollo P2P bitcoin, e poi estendere quel network a nodi che (e)seguono altri protocolli. Per esempio, il/i server Statum si connettono ai nodi che effettuano mining attraverso il protocollo Stratum del network bitcoin principale e collegano il protocollo Stratum al protocollo bitcoin P2P. Usiamo il termine "network di bitcoin esteso" (extended bitcoin network) per riferirsi a tutto il network generale che include il protocollo P2P bitcoin, i protocolli di pool-mining, il protocollo Stratum, e altri protocolli correlati che connettono i componenti al sistema bitcoin. Tipi di Nodi e Ruoli Anche se i nodi della rete P2P bitcoin sono uguali, possono avere differenti ruoli a seconda della funzionalità che stanno supportando. Un nodo bitcoin è una serie di funzioni: routing, database della blockchain, mining, e servizi wallet. Un nodo completo (full node) con tutte queste quattro caratteristiche è mostrato in Un nodo della rete bitcoin con tutte e quattro le funzioni: wallet, miner, database blockchain completo, e network routing. 1

145 Figure 1. Un nodo della rete bitcoin con tutte e quattro le funzioni: wallet, miner, database blockchain completo, e network routing All nodes include the routing function to participate in the network and might include other functionality. All nodes validate and propagate transactions and blocks, and discover and maintain connections to peers. In the full-node example in Un nodo della rete bitcoin con tutte e quattro le funzioni: wallet, miner, database blockchain completo, e network routing, the routing function is indicated by an orange circle named "Network Routing Node." Some nodes, called full nodes, also maintain a complete and up-to-date copy of the blockchain. Full nodes can autonomously and authoritatively verify any transaction without external reference. Some nodes maintain only a subset of the blockchain and verify transactions using a method called simplified payment verification, or SPV. These nodes are known as SPV or lightweight nodes. In the fullnode example in the figure, the full-node blockchain database function is indicated by a blue circle named "Full Blockchain." In La rete estesa di bitcoin che mostra vari tipi di nodi, gateway, e protocolli, 2

146 SPV nodes are drawn without the blue circle, showing that they do not have a full copy of the blockchain. Mining nodes compete to create new blocks by running specialized hardware to solve the proof-ofwork algorithm. Some mining nodes are also full nodes, maintaining a full copy of the blockchain, while others are lightweight nodes participating in pool mining and depending on a pool server to maintain a full node. The mining function is shown in the full node as a black circle named "Miner." User wallets might be part of a full node, as is usually the case with desktop bitcoin clients. Increasingly, many user wallets, especially those running on resource-constrained devices such as smartphones, are SPV nodes. The wallet function is shown in Un nodo della rete bitcoin con tutte e quattro le funzioni: wallet, miner, database blockchain completo, e network routing as a green circle named "Wallet". In addition to the main node types on the bitcoin P2P protocol, there are servers and nodes running other protocols, such as specialized mining pool protocols and lightweight client-access protocols. Diversi tipi di nodi della rete estesa di bitcoin mostra il tipi di nodi più comuni sulla rete bitcoin estesa. Il Network Bitcoin Esteso The main bitcoin network, running the bitcoin P2P protocol, consists of between 7,000 and 10,000 listening nodes running various versions of the bitcoin reference client (Bitcoin Core) and a few hundred nodes running various other implementations of the bitcoin P2P protocol, such as BitcoinJ, Libbitcoin, and btcd. A small percentage of the nodes on the bitcoin P2P network are also mining nodes, competing in the mining process, validating transactions, and creating new blocks. Various large companies interface with the bitcoin network by running full-node clients based on the Bitcoin Core client, with full copies of the blockchain and a network node, but without mining or wallet functions. These nodes act as network edge routers, allowing various other services (exchanges, wallets, block explorers, merchant payment processing) to be built on top. The extended bitcoin network includes the network running the bitcoin P2P protocol, described earlier, as well as nodes running specialized protocols. Attached to the main bitcoin P2P network are a number of pool servers and protocol gateways that connect nodes running other protocols. These other protocol nodes are mostly pool mining nodes (see [ch8]) and lightweight wallet clients, which do not carry a full copy of the blockchain. La rete estesa di bitcoin che mostra vari tipi di nodi, gateway, e protocolli mostra la rete estesa di bitcoin con i vari tipi di nodi, gateway server, edge router, e client wallet e i vari protocolli che essi usano per connettersi l un l altro. 3

147 4

148 Figure 2. Diversi tipi di nodi della rete estesa di bitcoin 5

149 6

150 Figure 3. La rete estesa di bitcoin che mostra vari tipi di nodi, gateway, e protocolli Network Discovery Quando un nuovo nodo viene avviato, deve scoprire altri nodi bitcoin presenti sulla rete per partecipare in essa. Per iniziare questo processo, un nuovo nodo deve scoprire almeno un nodo esistente sulla rete e connettervisi. La locazione geografica degli altri nodi è irrilevante; la tipologia del network bitcoin non è definita geograficamente. Perciò, ogni nodo bitcoin esistente può essere selezionato in modo casuale. To connect to a known peer, nodes establish a TCP connection, usually to port 8333 (the port generally known as the one used by bitcoin), or an alternative port if one is provided. Upon establishing a connection, the node will start a "handshake" (see L handshake iniziale tra peers) by transmitting a version message, which contains basic identifying information, including: PROTOCOL_VERSION Una costante che definisce la versione del protocollo P2P bitcoin che "parla" il client (e.g., 70002) nlocalservices Una lista di servizi locali supportati dal nodo, attualmente solo NODE_NETWORK ntime Il tempo attuale addryou L indirizzo IP del nodo remoto come è visto dal nodo corrente addrme L indirizzo IP del nodo locale, visto dal nodo locale subver Una sotto-versione che mostra il tipo di software in esecuzione su questo nodo (es., "/Satoshi: /")+ BestHeight L altezza del blocco della catena di blocchi di questo nodo (Vedi GitHub per un esempio di un esempio del messaggio di versione del network.) Il nodo peer risponde con verack per accettare e stabilire una connessione, e facoltativamente invia il suo messaggio version se vuole ricambiare la connessione e connettersi come peer. How does a new node find peers? The first method is to query DNS using a number of "DNS seeds," which are DNS servers that provide a list of IP addresses of bitcoin nodes. Some of those DNS seeds provide a static list of IP addresses of stable bitcoin listening nodes. Some of the DNS seeds are custom 7

151 implementations of BIND (Berkeley Internet Name Daemon) that return a random subset from a list of bitcoin node addresses collected by a crawler or a long-running bitcoin node. The Bitcoin Core client contains the names of five different DNS seeds. The diversity of ownership and diversity of implementation of the different DNS seeds offers a high level or reliability for the initial bootstrapping process. In the Bitcoin Core client, the option to use the DNS seeds is controlled by the option switch -dnsseed (set to 1 by default, to use the DNS seed). Alternatively, a bootstrapping node that knows nothing of the network must be given the IP address of at least one bitcoin node, after which it can establish connections through further introductions. The command-line argument -seednode can be used to connect to one node just for introductions, using it as a seed. After the initial seed node is used to form introductions, the client will disconnect from it and use the newly discovered peers. 8

152 Figure 4. L handshake iniziale tra peers Once one or more connections are established, the new node will send an addr message containing its own IP address to its neighbors. The neighbors will, in turn, forward the addr message to their neighbors, ensuring that the newly connected node becomes well known and better connected. Additionally, the newly connected node can send getaddr to the neighbors, asking them to return a list of IP addresses of other peers. That way, a node can find peers to connect to and advertise its existence on the network for other nodes to find it. La propagazione e la "scoperta" degli indirizzi shows the address discovery protocol. 9

153 Figure 5. La propagazione e la "scoperta" degli indirizzi A node must connect to a few different peers in order to establish diverse paths into the bitcoin network. Paths are not reliable nodes come and go and so the node must continue to discover new nodes as it loses old connections as well as assist other nodes when they bootstrap. Only one connection is needed to bootstrap, because the first node can offer introductions to its peer nodes and those peers can offer further introductions. It s also unnecessary and wasteful of network resources to connect to more than a handful of nodes. After bootstrapping, a node will remember its most recent successful peer connections, so that if it is rebooted it can quickly reestablish connections with its former peer network. If none of the former peers respond to its connection request, the node can use the seed nodes to bootstrap again. Su un nodo che sta eseguendo il client Bitcoin Core, puoi elencare le connessioni dei peer con il 10

154 comando getpeerinfo: $ bitcoin-cli getpeerinfo [ ] { }, { } "addr" : " :8333", "services" : " ", "lastsend" : , "lastrecv" : , "bytessent" : , "bytesrecv" : , "conntime" : , "pingtime" : , "version" : 70002, "subver" : "/Satoshi: /", "inbound" : false, "startingheight" : , "banscore" : 0, "syncnode" : true "addr" : " :8333", "services" : " ", "lastsend" : , "lastrecv" : , "bytessent" : , "bytesrecv" : , "conntime" : , "pingtime" : , "version" : 70001, "subver" : "/Satoshi:0.8.6/", "inbound" : false, "startingheight" : , "banscore" : 0, "syncnode" : false To override the automatic management of peers and to specify a list of IP addresses, users can provide the option -connect=<ipaddress> and specify one or more IP addresses. If this option is used, the node will only connect to the selected IP addresses, instead of discovering and maintaining the peer connections automatically. If there is no traffic on a connection, nodes will periodically send a message to maintain the 11

155 connection. If a node has not communicated on a connection for more than 90 minutes, it is assumed to be disconnected and a new peer will be sought. Thus, the network dynamically adjusts to transient nodes and network problems, and can organically grow and shrink as needed without any central control. Nodi Completi (Full Node) Full nodes are nodes that maintain a full blockchain with all transactions. More accurately, they probably should be called "full blockchain nodes." In the early years of bitcoin, all nodes were full nodes and currently the Bitcoin Core client is a full blockchain node. In the past two years, however, new forms of bitcoin clients have been introduced that do not maintain a full blockchain but run as lightweight clients. We ll examine these in more detail in the next section. Full blockchain nodes maintain a complete and up-to-date copy of the bitcoin blockchain with all the transactions, which they independently build and verify, starting with the very first block (genesis block) and building up to the latest known block in the network. A full blockchain node can independently and authoritatively verify any transaction without recourse or reliance on any other node or source of information. The full blockchain node relies on the network to receive updates about new blocks of transactions, which it then verifies and incorporates into its local copy of the blockchain. Running a full blockchain node gives you the pure bitcoin experience: independent verification of all transactions without the need to rely on, or trust, any other systems. It s easy to tell if you re running a full node because it requires 20+ gigabytes of persistent storage (disk space) to store the full blockchain. If you need a lot of disk and it takes two to three days to sync to the network, you are running a full node. That is the price of complete independence and freedom from central authority. There are a few alternative implementations of full blockchain bitcoin clients, built using different programming languages and software architectures. However, the most common implementation is the reference client Bitcoin Core, also known as the Satoshi client. More than 90% of the nodes on the bitcoin network run various versions of Bitcoin Core. It is identified as "Satoshi" in the sub-version string sent in the version message and shown by the command getpeerinfo as we saw earlier; for example, /Satoshi:0.8.6/. Exchanging "Inventory" The first thing a full node will do once it connects to peers is try to construct a complete blockchain. If it is a brand-new node and has no blockchain at all, it only knows one block, the genesis block, which is statically embedded in the client software. Starting with block #0 (the genesis block), the new node will have to download hundreds of thousands of blocks to synchronize with the network and re-establish the full blockchain. The process of syncing the blockchain starts with the version message, because that contains BestHeight, a node s current blockchain height (number of blocks). A node will see the version messages from its peers, know how many blocks they each have, and be able to compare to how many blocks it has in its own blockchain. Peered nodes will exchange a getblocks message that contains the 12

156 hash (fingerprint) of the top block on their local blockchain. One of the peers will be able to identify the received hash as belonging to a block that is not at the top, but rather belongs to an older block, thus deducing that its own local blockchain is longer than its peer s. The peer that has the longer blockchain has more blocks than the other node and can identify which blocks the other node needs in order to "catch up." It will identify the first 500 blocks to share and transmit their hashes using an inv (inventory) message. The node missing these blocks will then retrieve them, by issuing a series of getdata messages requesting the full block data and identifying the requested blocks using the hashes from the inv message. Let s assume, for example, that a node only has the genesis block. It will then receive an inv message from its peers containing the hashes of the next 500 blocks in the chain. It will start requesting blocks from all of its connected peers, spreading the load and ensuring that it doesn t overwhelm any peer with requests. The node keeps track of how many blocks are "in transit" per peer connection, meaning blocks that it has requested but not received, checking that it does not exceed a limit (MAX_BLOCKS_IN_TRANSIT_PER_PEER). This way, if it needs a lot of blocks, it will only request new ones as previous requests are fulfilled, allowing the peers to control the pace of updates and not overwhelming the network. As each block is received, it is added to the blockchain, as we will see in [blockchain]. As the local blockchain is gradually built up, more blocks are requested and received, and the process continues until the node catches up to the rest of the network. This process of comparing the local blockchain with the peers and retrieving any missing blocks happens any time a node goes offline for any period of time. Whether a node has been offline for a few minutes and is missing a few blocks, or a month and is missing a few thousand blocks, it starts by sending getblocks, gets an inv response, and starts downloading the missing blocks. I nodi sincronizzano la blockchain scaricando i blocchi da un altro nodo (peer) shows the inventory and block propagation protocol. Nodi di Simplified Payment Verification (SPV) Not all nodes have the ability to store the full blockchain. Many bitcoin clients are designed to run on space- and power-constrained devices, such as smartphones, tablets, or embedded systems. For such devices, a simplified payment verification (SPV) method is used to allow them to operate without storing the full blockchain. These types of clients are called SPV clients or lightweight clients. As bitcoin adoption surges, the SPV node is becoming the most common form of bitcoin node, especially for bitcoin wallets. I nodi SPV scaricano solo gli header del blocco e non scaricano le transazioni incluse in ogni blocco. La catena di blocchi risultante, senza transazioni, è volte più piccola della blockchain completa. I nodi SPV non possono avere una visione completa di tutte le UTXO che sono disponibili per essere spese perché non conoscono tutte le transazioni presenti sul network. I nodi SPV verificano le transazioni usando una metodologia leggermente diversa che si appoggia a nodi per ottenere una visione parziale dei componenti rilevanti della blockchain quando ne hanno bisogno. 13

157 14

158 Figure 6. I nodi sincronizzano la blockchain scaricando i blocchi da un altro nodo (peer) As an analogy, a full node is like a tourist in a strange city, equipped with a detailed map of every street and every address. By comparison, an SPV node is like a tourist in a strange city asking random strangers for turn-by-turn directions while knowing only one main avenue. Although both tourists can verify the existence of a street by visiting it, the tourist without a map doesn t know what lies down any of the side streets and doesn t know what other streets exist. Positioned in front of 23 Church Street, the tourist without a map cannot know if there are a dozen other "23 Church Street" addresses in the city and whether this is the right one. The mapless tourist s best chance is to ask enough people and hope some of them are not trying to mug him. Simplified payment verification verifies transactions by reference to their depth in the blockchain instead of their height. Whereas a full blockchain node will construct a fully verified chain of thousands of blocks and transactions reaching down the blockchain (back in time) all the way to the genesis block, an SPV node will verify the chain of all blocks (but not all transactions) and link that chain to the transaction of interest. For example, when examining a transaction in block 300,000, a full node links all 300,000 blocks down to the genesis block and builds a full database of UTXO, establishing the validity of the transaction by confirming that the UTXO remains unspent. An SPV node cannot validate whether the UTXO is unspent. Instead, the SPV node will establish a link between the transaction and the block that contains it, using a merkle path (see [merkle_trees]). Then, the SPV node waits until it sees the six blocks 300,001 through 300,006 piled on top of the block containing the transaction and verifies it by establishing its depth under blocks 300,006 to 300,001. The fact that other nodes on the network accepted block 300,000 and then did the necessary work to produce six more blocks on top of it is proof, by proxy, that the transaction was not a double-spend. An SPV node cannot be persuaded that a transaction exists in a block when the transaction does not in fact exist. The SPV node establishes the existence of a transaction in a block by requesting a merkle path proof and by validating the proof of work in the chain of blocks. However, a transaction s existence can be "hidden" from an SPV node. An SPV node can definitely prove that a transaction exists but cannot verify that a transaction, such as a double-spend of the same UTXO, doesn t exist because it doesn t have a record of all transactions. This vulnerability can be used in a denial-of-service attack or for a double-spending attack against SPV nodes. To defend against this, an SPV node needs to connect randomly to several nodes, to increase the probability that it is in contact with at least one honest node. This need to randomly connect means that SPV nodes also are vulnerable to network partitioning attacks or Sybil attacks, where they are connected to fake nodes or fake networks and do not have access to honest nodes or the real bitcoin network. Per scopi più pratici, i nodi SPV ben connessi sono abbastanza sicuri, trovando il giusto equilibrio di risorse necessarie, praticità e sicurezza. Per una sicurezza infallibile, tuttavia, niente batte l eseguire un full blockchain node. 15

159 TIP A full blockchain node verifies a transaction by checking the entire chain of thousands of blocks below it in order to guarantee that the UTXO is not spent, whereas an SPV node checks how deep the block is buried by a handful of blocks above it. To get the block headers, SPV nodes use a getheaders message instead of getblocks. The responding peer will send up to 2,000 block headers using a single headers message. The process is otherwise the same as that used by a full node to retrieve full blocks. SPV nodes also set a filter on the connection to peers, to filter the stream of future blocks and transactions sent by the peers. Any transactions of interest are retrieved using a getdata request. The peer generates a tx message containing the transactions, in response. Nodo di SPV nella fase di sincronizzazione degli header del blocco shows the synchronization of block headers. 16

160 Figure 7. Nodo di SPV nella fase di sincronizzazione degli header del blocco Because SPV nodes need to retrieve specific transactions in order to selectively verify them, they also create a privacy risk. Unlike full blockchain nodes, which collect all transactions within each block, the SPV node s requests for specific data can inadvertently reveal the addresses in their wallet. For example, a third party monitoring a network could keep track of all the transactions requested by a wallet on an SPV node and use those to associate bitcoin addresses with the user of that wallet, 17

161 destroying the user s privacy. Shortly after the introduction of SPV/lightweight nodes, the bitcoin developers added a feature called bloom filters to address the privacy risks of SPV nodes. Bloom filters allow SPV nodes to receive a subset of the transactions without revealing precisely which addresses they are interested in, through a filtering mechanism that uses probabilities rather than fixed patterns. Filtri di Bloom (Bloom Filter) A bloom filter is a probabilistic search filter, a way to describe a desired pattern without specifying it exactly. Bloom filters offer an efficient way to express a search pattern while protecting privacy. They are used by SPV nodes to ask their peers for transactions matching a specific pattern, without revealing exactly which addresses they are searching for. In our previous analogy, a tourist without a map is asking for directions to a specific address, "23 Church St." If she asks strangers for directions to this street, she inadvertently reveals her destination. A bloom filter is like asking, "Are there any streets in this neighborhood whose name ends in R-C-H?" A question like that reveals slightly less about the desired destination than asking for "23 Church St." Using this technique, a tourist could specify the desired address in more detail as "ending in U-R-C-H" or less detail as "ending in H." By varying the precision of the search, the tourist reveals more or less information, at the expense of getting more or less specific results. If she asks a less specific pattern, she gets a lot more possible addresses and better privacy, but many of the results are irrelevant. If she asks for a very specific pattern, she gets fewer results but loses privacy. Bloom filters serve this function by allowing an SPV node to specify a search pattern for transactions that can be tuned toward precision or privacy. A more specific bloom filter will produce accurate results, but at the expense of revealing what addresses are used in the user s wallet. A less specific bloom filter will produce more data about more transactions, many irrelevant to the node, but will allow the node to maintain better privacy. An SPV node will initialize a bloom filter as "empty" and in that state the bloom filter will not match any patterns. The SPV node will then make a list of all the addresses in its wallet and create a search pattern matching the transaction output that corresponds to each address. Usually, the search pattern is a pay-to-public-key-hash script that is the expected locking script that will be present in any transaction paying to the public-key-hash (address). If the SPV node is tracking the balance of a P2SH address, the search pattern will be a pay-to-script-hash script, instead. The SPV node then adds each of the search patterns to the bloom filter, so that the bloom filter can recognize the search pattern if it is present in a transaction. Finally, the bloom filter is sent to the peer and the peer uses it to match transactions for transmission to the SPV node. Bloom filters are implemented as a variable-size array of N binary digits (a bit field) and a variable number of M hash functions. The hash functions are designed to always produce an output that is between 1 and N, corresponding to the array of binary digits. The hash functions are generated deterministically, so that any node implementing a bloom filter will always use the same hash functions and get the same results for a specific input. By choosing different length (N) bloom filters 18

162 and a different number (M) of hash functions, the bloom filter can be tuned, varying the level of accuracy and therefore privacy. In Un esempio di un filtro bloom semplice, con un campo a 16-bit e tre funzioni di hashing, usiamo un array molto piccolo di 16 bit e una serie di tre funzioni di hashing per dimostrare come funzionano i bloom filter. Figure 8. Un esempio di un filtro bloom semplice, con un campo a 16-bit e tre funzioni di hashing The bloom filter is initialized so that the array of bits is all zeros. To add a pattern to the bloom filter, the pattern is hashed by each hash function in turn. Applying the first hash function to the input results in a number between 1 and N. The corresponding bit in the array (indexed from 1 to N) is found and set to 1, thereby recording the output of the hash function. Then, the next hash function is used to set another bit and so on. Once all M hash functions have been applied, the search pattern will be "recorded" in the bloom filter as M bits that have been changed from 0 to 1. Aggiungendo un pattern "A" al nostro filtro bloom semplice è un esempio di aggiunta di un pattern "A" al semplice filtro bloom mostrato in Un esempio di un filtro bloom semplice, con un campo a 16-bit e tre funzioni di hashing. Adding a second pattern is as simple as repeating this process. The pattern is hashed by each hash function in turn and the result is recorded by setting the bits to 1. Note that as a bloom filter is filled with more patterns, a hash function result might coincide with a bit that is already set to 1, in which case the bit is not changed. In essence, as more patterns record on overlapping bits, the bloom filter starts to become saturated with more bits set to 1 and the accuracy of the filter decreases. This is why the filter is a probabilistic data structure it gets less accurate as more patterns are added. The accuracy depends on the number of patterns added versus the size of the bit array (N) and number of hash functions (M). A larger bit array and more hash functions can record more patterns with higher accuracy. A smaller bit array or fewer hash functions will record fewer patterns and produce less accuracy. 19

163 Figure 9. Aggiungendo un pattern "A" al nostro filtro bloom semplice Aggiungendo un secondo pattern "B" al nostro filtro bloom semplice è un esempio di aggiunta di un secondo pattern "B" al filtro bloom semplice. Figure 10. Aggiungendo un secondo pattern "B" al nostro filtro bloom semplice To test if a pattern is part of a bloom filter, the pattern is hashed by each hash function and the 20

164 resulting bit pattern is tested against the bit array. If all the bits indexed by the hash functions are set to 1, then the pattern is probably recorded in the bloom filter. Because the bits may be set because of overlap from multiple patterns, the answer is not certain, but is rather probabilistic. In simple terms, a bloom filter positive match is a "Maybe, Yes." Testing the existence of pattern "X" in the bloom filter. The result is probabilistic positive match, meaning "Maybe." è un esempio di controllo dell esistenza di un pattern "X" nel filtro bloom semplice. I bit corrispondenti sono impostati a 1, quindi il pattern probabilmente è una corrispondenza. Figure 11. Testing the existence of pattern "X" in the bloom filter. The result is probabilistic positive match, meaning "Maybe." On the contrary, if a pattern is tested against the bloom filter and any one of the bits is set to 0, this proves that the pattern was not recorded in the bloom filter. A negative result is not a probability, it is a certainty. In simple terms, a negative match on a bloom filter is a "Definitely Not!" Testando l esistenza del pattern "Y" nel filtro bloom. Il risultato sarà una corrispondenza definitiva negativa, che sta a significare "Sicuramente No!" is an example of testing the existence of pattern "Y" in the simple bloom filter. One of the corresponding bits is set to 0, so the pattern is definitely not a match. 21

165 Figure 12. Testando l esistenza del pattern "Y" nel filtro bloom. Il risultato sarà una corrispondenza definitiva negativa, che sta a significare "Sicuramente No!" Bitcoin s implementation of bloom filters is described in Bitcoin Improvement Proposal 37 (BIP0037). See [appdxbitcoinimpproposals] or visit GitHub. I Bloom Filters e gli Inventory Updates (Aggiornamenti di Inventario) Bloom filters are used to filter the transactions (and blocks containing them) that an SPV node receives from its peers. SPV nodes will create a filter that matches only the addresses held in the SPV node s wallet. The SPV node will then send a filterload message to the peer, containing the bloom filter to use on the connection. After a filter is established, the peer will then test each transaction s outputs against the bloom filter. Only transactions that match the filter are sent to the node. In response to a getdata message from the node, peers will send a merkleblock message that contains only block headers for blocks matching the filter and a merkle path (see [merkle_trees]) for each matching transaction. The peer will then also send tx messages containing the transactions matched by the filter. The node setting the bloom filter can interactively add patterns to the filter by sending a filteradd message. To clear the bloom filter, the node can send a filterclear message. Because it is not possible to remove a pattern from a bloom filter, a node has to clear and resend a new bloom filter if a pattern is no longer desired. 22

166 Gruppo di Transazioni (Transaction Pools) Almost every node on the bitcoin network maintains a temporary list of unconfirmed transactions called the memory pool, mempool, or transaction pool. Nodes use this pool to keep track of transactions that are known to the network but are not yet included in the blockchain. For example, a node that holds a user s wallet will use the transaction pool to track incoming payments to the user s wallet that have been received on the network but are not yet confirmed. Man mano che le transazioni sono ricevute e verificate, sono aggiunte alla pool delle transazioni e trasmesse ai nodi vicini che le propagano sul network. Some node implementations also maintain a separate pool of orphaned transactions. If a transaction s inputs refer to a transaction that is not yet known, such as a missing parent, the orphan transaction will be stored temporarily in the orphan pool until the parent transaction arrives. When a transaction is added to the transaction pool, the orphan pool is checked for any orphans that reference this transaction s outputs (its children). Any matching orphans are then validated. If valid, they are removed from the orphan pool and added to the transaction pool, completing the chain that started with the parent transaction. In light of the newly added transaction, which is no longer an orphan, the process is repeated recursively looking for any further descendants, until no more descendants are found. Through this process, the arrival of a parent transaction triggers a cascade reconstruction of an entire chain of interdependent transactions by re-uniting the orphans with their parents all the way down the chain. Both the transaction pool and orphan pool (where implemented) are stored in local memory and are not saved on persistent storage; rather, they are dynamically populated from incoming network messages. When a node starts, both pools are empty and are gradually populated with new transactions received on the network. Some implementations of the bitcoin client also maintain a UTXO database or UTXO pool, which is the set of all unspent outputs on the blockchain. Although the name "UTXO pool" sounds similar to the transaction pool, it represents a different set of data. Unlike the transaction and orphan pools, the UTXO pool is not initialized empty but instead contains millions of entries of unspent transaction outputs, including some dating back to The UTXO pool may be housed in local memory or as an indexed database table on persistent storage. Whereas the transaction and orphan pools represent a single node s local perspective and might vary significantly from node to node depending upon when the node was started or restarted, the UTXO pool represents the emergent consensus of the network and therefore will vary little between nodes. Furthermore, the transaction and orphan pools only contain unconfirmed transactions, while the UTXO pool only contains confirmed outputs. Messaggi di Avviso Alert messages are a seldom used function, but are nevertheless implemented in most nodes. Alert 23

167 messages are bitcoin s "emergency broadcast system," a means by which the core bitcoin developers can send an emergency text message to all bitcoin nodes. This feature is implemented to allow the core developer team to notify all bitcoin users of a serious problem in the bitcoin network, such as a critical bug that requires user action. The alert system has only been used a handful of times, most notably in early 2013 when a critical database bug caused a multiblock fork to occur in the bitcoin blockchain. Alert messages are propagated by the alert message. The alert message contains several fields, including: ID Un identificatore dell alert cosí che gli alert doppioni possono essere rilevati Expiration Un unità di tempo dopo la quale l alert scade RelayUntil Un unità di tempo dopo la quale l alert non dovrebbe essere mostrato MinVer, MaxVer Il range di versioni del protocollo bitcoin a cui si applica subver La versione del software client a cui questo alert si applica Priority Un livello di priorità d allerta, attualmente inutilizzato Alerts are cryptographically signed by a public key. The corresponding private key is held by a few select members of the core development team. The digital signature ensures that fake alerts will not be propagated on the network. Each node receiving this alert message will verify it, check for expiration, and propagate it to all its peers, thus ensuring rapid propagation across the entire network. In addition to propagating the alert, the nodes might implement a user interface function to present the alert to the user. In the Bitcoin Core client, the alert is configured with the command-line option -alertnotify, which specifies a command to run when an alert is received. The alert message is passed as a parameter to the alertnotify command. Most commonly, the alertnotify command is set to generate an message to the administrator of the node, containing the alert message. The alert is also displayed as a pop-up dialog in the graphical user interface (bitcoin-qt) if it is running. Other implementations of the bitcoin protocol might handle the alert in different ways. Many hardware-embedded bitcoin mining systems do not implement the alert message function because they have no user interface. It is strongly recommended that miners running such mining systems subscribe to alerts via a mining pool operator or by running a lightweight node just for alert purposes. 24

168 La Blockchain Introduzione I dati della struttura dati blockchain sono un ordinata, back-linked list di blocchi di transazioni. La blockchain può essere salvata come un file piatto, o in un semplice database. Il client Bitcoin Core salva i metadati della blockchain usando il database LevelDB (libreria C scritta dai programmatori che lavorano a Google). I blocchi sono collegati "indietro", ognuno si riferisce al blocco precedente presente nella catena. La blockchain è spesso visualizzata come una pila verticale, con blocchi stratificati l uno sopra l altro e il primo blocco serve da fondamenta della pila. La visualizzazione dei blocchi impilati uno sopra l altro provoca l uso di terminologie come "altezza" (height) per riferirsi alla distanza dal primo blocco, e "top" o "tip" (cima o punta) per riferirsi al blocco aggiunto più recentemente. Ogni blocco contenuto nella blockchain è identificato da un hash, generato usando l algoritmo crittografico di hashing SHA256 sull header del blocco. Ogni blocco inoltre referenzia il blocco precedente, conosciuto anche come parent block, attraverso il campo "previous block hash" nel block header. La sequenza di hash che collegano ogni blocco al proprio parent crea una catena che si collega, blocco per blocco fino al primo blocco creato, conosciuto con il nome di, ovvero blocco di genesi. Anche se un blocco ha solo un genitore, può temporaneamente avere multipli figli. Ognuno dei figli si riferisce allo stesso blocco del padre e contiene lo stesso hash (padre) nel campo "previous block hash" (hash del blocco precedente). Multipli figli emergono durante un "fork" (biforcazione) della blockchain, una situazione temporanea che occorre quando differenti blocchi sono scoperti quasi simultaneamente da miner differenti (vedi [forks]). Eventualmente, solo un blocco figlio diventa parte della blockchain e la "biforcazione" viene risolta. Anche se un blocco può avere più di un figlo, ogni blocco può avere solo un genitore. Questo perchè un blocco ha un singolo campo "hash del blocco precedente" (previous block hash) che si riferisce al suo singolo genitore. Il campo "previous block hash" è dentro l header del blocco e per questo influenza l hash del blocco attuale. L identità stessa del figlio cambia nel caso in cui cambi l identità del genitore. Quando il genitore viene modificato in qualsiasi modo, l hash del genitore cambia. L hash modificato del genitore necessita un cambio nel puntatore "previous block hash" del figlio. Questo a sua volta causa il cambio dell hash del figlio, che richiede il cambio nel puntatore dell hash nipote, che a sua volta cambia il puntamento al nipote, e così via Questo effetto a cascata assicura che fino a quando un blocco ha tante generazioni di blocchi che lo seguono, non può essere modificato senza forzare un ricalcolo su tutti i blocchi seguenti. Visto che per questo ricalcolo servirebbe un enorme potenza computazionale, l esistenza di una lunga catena di blocchi fa si che la storia più profonda della blockchain sia immutabile, che è una degli elementi chiave della sicurezza di bitcoin. Un modo di pensare alla blockchain è come ai livelli di una stratificazione geologica, o a una carota di ghiaccio. Gli strati superficiali possono cambiare con le stagioni o anche essere eliminati prima che abbiano il tempo di depositarsi, ma se si scende di pochi centimetri gli strati geologici diventano sempre più stabili. Al punto che arrivi a guardare poche centinaia di metri sotto stai vedendo una foto del passato che è stata lasciata intatta da milioni di anni. Nella blockchain i blocchi più recenti 1

169 potrebbero cambiare se c è un fork. Gli ultimi sei blocchi sono come alcuni centimentri del suolo. Ma se vai più in profondità nella blockchain, oltre sei blocchi, i blocchi hanno sempre meno probabilità di essere modifcati. Dopo 100 blocchi c è così tanta solidita che la transazione di coinbase - una transazione contenente i nuovi bitcoin minati - può essere spesa. Alcune migliaia di blocchi indietro (un mese), e la blockchain è saldata nella storia, per qualunque tipo di dato. Mentre il protocollo permette sempre che una catena possa essere sostituita da una catena più lunga ed esiste sempre la possibilità che una catena diventi reversibile, la possibilità che questo accada diminuisce coi blocchi fino a diventare infinitesima. Struttura del Blocco A block is a container data structure that aggregates transactions for inclusion in the public ledger, the blockchain. The block is made of a header, containing metadata, followed by a long list of transactions that make up the bulk of its size. The block header is 80 bytes, whereas the average transaction is at least 250 bytes and the average block contains more than 500 transactions. A complete block, with all transactions, is therefore 1,000 times larger than the block header. La struttura di un blocco describes the structure of a block. Table 1. La struttura di un blocco Dimensione Campo Descrizione 4 byte Dimensione del Blocco (Block Size) 80 bytes Header del Blocco (Block Header) 1-9 byte (VarInt) Contatore di transazione (Transaction Counter) La dimensione del blocco, in byte Multipli campi dall header del blocco Quante transazioni seguono Variabile Transazioni Le transazioni registrate nel blocco Header del Blocco The block header consists of three sets of block metadata. First, there is a reference to a previous block hash, which connects this block to the previous block in the blockchain. The second set of metadata, namely the difficulty, timestamp, and nonce, relate to the mining competition, as detailed in [ch8]. The third piece of metadata is the merkle tree root, a data structure used to efficiently summarize all the transactions in the block. La struttura di un block header describes the structure of a block header. Table 2. La struttura di un block header 2

170 Dimensione Campo Descrizione 4 byte Versione Un numero di versione per tracciare upgrade al software e/o al protocollo 32 byte Hash del Blocco Precedente Un riferimento all hash del blocco precedente (genitore) nella chain 32 byte Merkle Root Un hash della radice del merkle tree delle transazioni di questo blocco 4 byte Timestamp Il tempo approssimato della creazione del blocco corrente (secondi dalla Unix Epoch) 4 bytes Target di Difficoltà (Difficulty Target) Il target di difficoltà dell algoritmo di proof-of-work per questo blocco 4 byte Nonce Un contatore utilizzato per l algoritmo di proof-of-work Il nonce, il target di difficoltà, e il timestamp sono usati nel processo di mining e saranno discussi in maggiore dettaglio nel [ch8]. Identificatori di blocco: Hash del Block Header e Altezza del Blocco (Block Height) The primary identifier of a block is its cryptographic hash, a digital fingerprint, made by hashing the block header twice through the SHA256 algorithm. The resulting 32-byte hash is called the <em>block hash</em> but is more accurately the <em>block header hash</em>, <phrase role="keeptogether">because only the block header is used to compute it. For example,</phrase> d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f is the block hash of the first bitcoin block ever created. The block hash identifies a block uniquely and unambiguously and can be independently derived by any node by simply hashing the block header. Note that the block hash is not actually included inside the block s data structure, neither when the block is transmitted on the network, nor when it is stored on a node s persistence storage as part of the blockchain. Instead, the block s hash is computed by each node as the block is received from the network. The block hash might be stored in a separate database table as part of the block s metadata, to facilitate indexing and faster retrieval of blocks from disk. A second way to identify a block is by its position in the blockchain, called the <phrase role="keeptogether"><emphasis>block height</emphasis>. The first block ever created is at block height 0 (zero) and is the</phrase> <phrase role="keep-together">same block that was previously referenced by the 3

171 following block hash</phrase> d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f. A block can thus be identified two ways: by referencing the block hash or by referencing the block height. Each subsequent block added "on top" of that first block is one position "higher" in the blockchain, like boxes stacked one on top of the other. The block height on January 1, 2014, was approximately 278,000, meaning there were 278,000 blocks stacked on top of the first block created in January Unlike the block hash, the block height is not a unique identifier. Although a single block will always have a specific and invariant block height, the reverse is not true the block height does not always identify a single block. Two or more blocks might have the same block height, competing for the same position in the blockchain. This scenario is discussed in detail in the section [forks]. The block height is also not a part of the block s data structure; it is not stored within the block. Each node dynamically identifies a block s position (height) in the blockchain when it is received from the bitcoin network. The block height might also be stored as metadata in an indexed database table for faster retrieval. TIP A block s block hash always identifies a single block uniquely. A block also always has a specific block height. However, it is not always the case that a specific block height can identify a single block. Rather, two or more blocks might compete for a single position in the blockchain. Il Genesis Block The first block in the blockchain is called the genesis block and was created in It is the common ancestor of all the blocks in the blockchain, meaning that if you start at any block and follow the chain backward in time, you will eventually arrive at the genesis block. Every node always starts with a blockchain of at least one block because the genesis block is statically encoded within the bitcoin client software, such that it cannot be altered. Every node always "knows" the genesis block s hash and structure, the fixed time it was created, and even the single transaction within. Thus, every node has the starting point for the blockchain, a secure "root" from which to build a trusted blockchain. Visualizza il genesis block staticamente encoded nel client Bitcoin Core, in chainparams.cpp. Il seguente hash identificativo appartiene al genesis block: d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f Puoi cercare quel block hash in un qualsiasi sito block explorer, come blockchain.info, e troverai una pagina che descrive il contenuto di questo blocco, con un URL contenente quell hash: 4

172 26f Usando il client di riferimento Bitcoin Core da riga di comando: $ bitcoind getblock d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f { } "hash" : " d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", "confirmations" : , "size" : 285, "height" : 0, "version" : 1, "merkleroot" : "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", "tx" : [ "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b" ], "time" : , "nonce" : , "bits" : "1d00ffff", "difficulty" : , "nextblockhash" : " a8e6886ab5951d76f afc90947ee320161bbf18eb6048" The genesis block contains a hidden message within it. The coinbase transaction input contains the text "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks." This message was intended to offer proof of the earliest date this block was created, by referencing the headline of the British newspaper The Times. It also serves as a tongue-in-cheek reminder of the importance of an independent monetary system, with bitcoin s launch occurring at the same time as an unprecedented worldwide monetary crisis. The message was embedded in the first block by Satoshi Nakamoto, bitcoin s creator. Collegando i Blocchi nella Blockchain Bitcoin full nodes maintain a local copy of the blockchain, starting at the genesis block. The local copy of the blockchain is constantly updated as new blocks are found and used to extend the chain. As a node receives incoming blocks from the network, it will validate these blocks and then link them to the existing blockchain. To establish a link, a node will examine the incoming block header and look for the "previous block hash." Assumiamo, per esempio, che il nodo abbia 277,314 blocchi nella copia locale della blockchain. L ultimo blocco del quale il nodo sa qualcosa è il blocco 277,314, con un hash dell header del blocco di e7ba6fe7bad39faf3b5a83daed765f05f7d1b71a Il nodo bitcoin in seguito riceve un nuovo blocco dalla rete, che lo analizza come riportato qui: 5

173 { "size" : 43560, "version" : 2, "previousblockhash" : " e7ba6fe7bad39faf3b5a83daed765f05f7d1b71a ", "merkleroot" : "5e049f4030e0ab2debb92378f53c0a6e09548aea083f3ab25e1d94ea1155e29d", "time" : , "difficulty" : , "nonce" : , "tx" : [ "257e7497fb8bc68421eb2c7b699dbab e7352f0d9e6522c7cf3f6c77", #[... molte altre transazioni omesse...] } ] "05cfd38f6ae6aa83674cc99e4d75a1458c165b7ab84725eda41d018a " Osservando questo nuovo blocco, possiamo notare che il nodo trova il campo previousblockhash, che contiene l hash del blocco genitore. E' un hash conosciuto al nodo, come l ultimo blocco della chain all altezza (block height) 277,314. Quindi questo nuovo blocco è un figlio dell ultimo blocco della chain e estende la blockchain esistente. Il nodo aggiunge questo nuovo blocco alla fine della catena (chain), rendendo la blockchain più lunga con una nuova height di 277,315. Blocchi collegati in una catena, per referenza al precedente hash dell header del blocco mostra la chain di tre blocchi, collegati da referenze nel campo previousblockhash. I Merkle Tree Each block in the bitcoin blockchain contains a summary of all the transactions in the block, using a merkle tree. A merkle tree, also known as a binary hash tree, is a data structure used for efficiently summarizing and verifying the integrity of large sets of data. Merkle trees are binary trees containing cryptographic hashes. The term "tree" is used in computer science to describe a branching data structure, but these trees are usually displayed upside down with the "root" at the top and the "leaves" at the bottom of a diagram, as you will see in the examples that follow. 6

174 7

175 Figure 1. Blocchi collegati in una catena, per referenza al precedente hash dell header del blocco Merkle trees are used in bitcoin to summarize all the transactions in a block, producing an overall digital fingerprint of the entire set of transactions, providing a very efficient process to verify whether a transaction is included in a block. A Merkle tree is constructed by recursively hashing pairs of nodes until there is only one hash, called the root, or merkle root. The cryptographic hash algorithm used in bitcoin s merkle trees is SHA256 applied twice, also known as double-sha256. When N data elements are hashed and summarized in a merkle tree, you can check to see if any one data element is included in the tree with at most 2*log~2~(N) calculations, making this a very efficient data structure. Il merkle tree è costruito dal basso verso l alto. Nel seguente esempio, partiamo con quattro transazioni, A, B, C e D, che formano le foglie del Merkle tree, come mostrato in Calcolando i nodi in un merkle tree. Le transazioni non sono salvate nel merkle tree; invece, i loro dati sono hash-ati e l hash risultante è salvato in ogni nodo figlia come H A, H B, H C, e H D : H~A~ = SHA256(SHA256(Transaction A)) Consecutive pairs of leaf nodes are then summarized in a parent node, by concatenating the two hashes and hashing them together. For example, to construct the parent node H AB, the two 32-byte hashes of the children are concatenated to create a 64-byte string. That string is then double-hashed to produce the parent node s hash: H~AB~ = SHA256(SHA256(H~A~ + H~B~)) The process continues until there is only one node at the top, the node known as the Merkle root. That 32-byte hash is stored in the block header and summarizes all the data in all four transactions. 8

176 Figure 2. Calcolando i nodi in un merkle tree Visto che il merkle tree è un albero binario, necessita di un numero pari di nodi foglia. Se il numero di transazioni da sintetizzare è un numero pari, l ultimo hash di transazione sarà duplicato per creare un numero pari di nodi foglia, questo tipo di alberi sono conosciuti come alberi bilanciati. Il tutto è mostrato in Duplicando un elemento (data element) ottiene un numero di elementi pari, dove la transazione C è duplicata. Figure 3. Duplicando un elemento (data element) ottiene un numero di elementi pari The same method for constructing a tree from four transactions can be generalized to construct trees of any size. In bitcoin it is common to have several hundred to more than a thousand transactions in a 9

177 single block, which are summarized in exactly the same way, producing just 32 bytes of data as the single merkle root. In Un merkle tree che riassume tanti data element, you will see a tree built from 16 transactions. Note that although the root looks bigger than the leaf nodes in the diagram, it is the exact same size, just 32 bytes. Whether there is one transaction or a hundred thousand transactions in the block, the merkle root always summarizes them into 32 bytes. To prove that a specific transaction is included in a block, a node only needs to produce log~2~(n) 32- byte hashes, constituting an authentication path or merkle path connecting the specific transaction to the root of the tree. This is especially important as the number of transactions increases, because the base-2 logarithm of the number of transactions increases much more slowly. This allows bitcoin nodes to efficiently produce paths of 10 or 12 hashes ( bytes), which can provide proof of a single transaction out of more than a thousand transactions in a megabyte-size block. Figure 4. Un merkle tree che riassume tanti data element In Un merkle path usato per provare l inclusione di un data element, a node can prove that a transaction K is included in the block by producing a merkle path that is only four 32-byte hashes long (128 bytes total). The path consists of the four hashes (noted in blue in Un merkle path usato per provare l inclusione di un data element) H L, H IJ, H MNOP and H ABCDEFGH. With those four hashes provided as an authentication path, any node can prove that H K (noted in green in the diagram) is included in the merkle root by computing four additional pair-wise hashes H KL, H IJKL, H IJKLMNOP, and the merkle tree root (outlined in a dotted line in the diagram). 10

178 Figure 5. Un merkle path usato per provare l inclusione di un data element Il codice nel Costruendo un merkle tree dimostra il processo di creazione di un merkle tree dagli hash del nodo-foglia fino alla radice, usando la libreria libbitcoin per qualche funzione helper. Example 1. Costruendo un merkle tree #include <bitcoin/bitcoin.hpp> bc::hash_digest create_merkle(bc::hash_list& merkle) { // Stop if hash list is empty. if (merkle.empty()) return bc::null_hash; else if (merkle.size() == 1) return merkle[0]; // While there is more than 1 hash in the list, keep looping... while (merkle.size() > 1) { // If number of hashes is odd, duplicate last hash in the list. if (merkle.size() % 2!= 0) merkle.push_back(merkle.back()); // List size is now even. assert(merkle.size() % 2 == 0); // New hash list. bc::hash_list new_merkle; // Loop through hashes 2 at a time. for (auto it = merkle.begin(); it!= merkle.end(); it += 2) { // Join both current hashes together (concatenate). bc::data_chunk concat_data(bc::hash_size * 2); 11

179 auto concat = bc::make_serializer(concat_data.begin()); concat.write_hash(*it); concat.write_hash(*(it + 1)); assert(concat.iterator() == concat_data.end()); // Hash both of the hashes. bc::hash_digest new_root = bc::bitcoin_hash(concat_data); // Add this to the new list. new_merkle.push_back(new_root); } // This is the new list. merkle = new_merkle; } // DEBUG output std::cout << "Current merkle hash list:" << std::endl; for (const auto& hash: merkle) std::cout << " " << bc::encode_hex(hash) << std::endl; std::cout << std::endl; // } // Finally we end up with a single item. return merkle[0]; int main() { // Replace these hashes with ones from a block to reproduce the same merkle root. bc::hash_list tx_hashes{{ bc::hash_literal(" "), bc::hash_literal(" "), bc::hash_literal(" "), }}; const bc::hash_digest merkle_root = create_merkle(tx_hashes); std::cout << "Result: " << bc::encode_hex(merkle_root) << std::endl; return 0; } Compilando e eseguendo il codice di esempio dell esempio merkle mostra il risultato della compilazione e esecuzione del codice merkle. 12

180 Example 2. Compilando e eseguendo il codice di esempio dell esempio merkle $ # Compila il codice in merkle.cpp $ g++ -o merkle merkle.cpp $(pkg-config --cflags --libs libbitcoin) $ # Esegui l'eseguibile merkle $./merkle Lista di hash merkle corrente: a0418e4380db0af d8b65424d397170b8499cdc28c4d db96905c8dc8b99398ca1cd5bd5b84ac3264a4e1b3e65afa1bcee7540c4 Lista di hash merkle corrente: d47780c084bad3830bcdaf6eace035e4c6cbf646d103795d22104fb105014ba3 Risultato: d47780c084bad3830bcdaf6eace035e4c6cbf646d103795d22104fb105014ba3 The efficiency of merkle trees becomes obvious as the scale increases. Efficenza del merkle tree shows the amount of data that needs to be exchanged as a merkle path to prove that a transaction is part of a block. Table 3. Efficenza del merkle tree Numero di transazioni Dimensione approssimativa del blocco Dimensione del path (hash) Dimensione del path (byte) 16 transazioni 4 kilobyte 4 hash 128 byte 512 transazioni 128 kilobyte 9 hash 288 byte 2048 transazioni 512 kilobyte 11 hash 352 byte 65,535 transazioni 16 megabyte 16 hash 512 byte As you can see from the table, while the block size increases rapidly, from 4 KB with 16 transactions to a block size of 16 MB to fit 65,535 transactions, the merkle path required to prove the inclusion of a transaction increases much more slowly, from 128 bytes to only 512 bytes. With merkle trees, a node can download just the block headers (80 bytes per block) and still be able to identify a transaction s inclusion in a block by retrieving a small merkle path from a full node, without storing or transmitting the vast majority of the blockchain, which might be several gigabytes in size. Nodes that do not maintain a full blockchain, called simplified payment verification (SPV nodes), use merkle paths to verify transactions without downloading full blocks. Merkle Tree e Simplified Payment Verification (SPV) I merkle trees sono usati estensivamente dai nodi SPV (o VSP in italiano - Verifica Semplificata del Pagamento, ndt). I nodi SPV non hanno tutte le transazioni e non scaricano blocchi completi, ma solo 13

181 header dei blocchi. Per verificare che una transazione sia inclusa in un blocco, senza dover scaricare tutte le transazioni nel blocco, essi utilizzano un percorso di autenticazione, chiamato anche merkle path. Consider, for example, an SPV node that is interested in incoming payments to an address contained in its wallet. The SPV node will establish a bloom filter on its connections to peers to limit the transactions received to only those containing addresses of interest. When a peer sees a transaction that matches the bloom filter, it will send that block using a merkleblock message. The merkleblock message contains the block header as well as a merkle path that links the transaction of interest to the merkle root in the block. The SPV node can use this merkle path to connect the transaction to the block and verify that the transaction is included in the block. The SPV node also uses the block header to link the block to the rest of the blockchain. The combination of these two links, between the transaction and block, and between the block and blockchain, proves that the transaction is recorded in the blockchain. All in all, the SPV node will have received less than a kilobyte of data for the block header and merkle path, an amount of data that is more than a thousand times less than a full block (about 1 megabyte currently). 14

182 Il Mining e Il Consenso Introduzione Il Mining è il processo in cui nuovi bitcoin sono aggiunti al totale di moneta in circolazione. Il Mining inoltre serve per proteggere il sistema bitcoin contro transazioni fraudolente o transazioni che cercano di spendere lo stesso numero di bitcoin più di una volta, problema conosciuto con il nome di doublespend (doppia-spesa). I miner provvedono alla potenza di calcolo per il network bitcoin in cambio dell opportunità di essere ricompensati con dei bitcoin. I miner validano nuove transazioni e le registrano sulla ledger globale (un libro mastro globale). Un nuovo blocco, contenente le transazioni che sono avvenute dopo la scoperta dell ultimo blocco, è "mined" in media ogni 10 minuti, e inoltre aggiungendo queste transazioni alla blockchain. Le transazioni che sono diventate parte di un blocco e aggiunte alla blockchain sono considerate "confermate", questo permette ai nuovi proprietari dei bitcoin di spendere i bitcoin ricevuti nelle suddette transazioni. I miner ricevono due tipi di ricompense per il lavoro di mining: i nuovi bitcoin creati ogni nuovo blocco, e le commissioni (fee) di transazione da tutte le transazioni incluse nel blocco. Per ottenere questa ricompensa, i miner devono competere nel risolvere un difficile problema matematico basato su un algoritmo crittografico di hashing. La soluzione al problema, chiamato proof of work, è incluso nel nuovo blocco e agisce come prova che il miner ha impiegato uno sforzo computazionale adeguato. La gara a risolvere l algoritmo di proof-of-work per ottenere la ricompensa e il diritto di registrare le transazioni nella blockchain è alla base del modello di sicurezza di bitcoin. Il processo di generazione di nuova moneta è chiamato mining perchè la ricompensa è fatta per stimulare il rendimento decrescente, con lo stesso funzionamento dell estrazione (mining - ndt) di metalli preziosi. La massa monetaria di Bitcoin è creata attraverso appunto questa estrazione, il mining, nello stesso modo in cui una banca centrale emette nuova moneta con la stampa delle banconote. La somma di nuovi bitcoin creati che un miner può aggiungere in un blocco decresce approssimativamente ogni quattro anni (o precisamente ogni blocchi). E' iniziata con 50 bitcoin per blocco nel Gennaio del 2009 e si è dimezzata a 25 bitcoin per blocco nel Novembre del Si dimezzerà nuovamente a 12.5 bitcoin per blocco a qualche punto nel 2016 (probabilmente verso ottobre n.d.t.). Basato su questa formula, la ricompensa del mining di bitcoin decresce esponenzialmente fino approssimativamente all anno 2140, quando tutti i bicoin ( million) saranno stati emessi. Dopo il 2140, nessun nuovo bicoin verrà emesso. I miner bitcoin inoltre guadagnano un compenso dalle transazioni. Ogni transazione può includere una fee di transazione, nella forma di un surplus di bitcoin tra gli input e gli output della transazione. Il miner bitcoin vincente può "tenere il resto" della transazione inclusa nel blocco vincente. Ad oggi, le fee rappresentano 0.5% o meno delle entrate di un miner bitcoin, la maggior parte derivanti dal conio dei nuovi bitcoin. In ogni caso, visto che la ricompensa diminuisce nel tempo e il numero di transazioni per blocco aumenta, una maggiore proporzione deggli introiti ottenuti con il mining di bitcoin proverrà dalle fee. Dopo il 2140, tutti i guadagni dei miner bitcoin saranno nella forma di fee di 1

183 transazione. La parola "mining" è in qualche modo ingannevole. Evocando l estrazione di metalli preziosi, concentra la nostra attenzione nella ricompensa del mining, i nuovi bitcoin in ogni nuovo blocco. Anche se il mining è incentivato da questa ricompensa, il primo scopo del mining non è la ricompensa o la generazione di nuova moneta. Se vedi il mining solo come il processo nel quale la moneta è creata, ne stai confondendo i mezzi (gli incentivi) come se fossero il traguardo del processo. Il mining è il processo centrale della clearing house (camera di compensazione bancaria), col quale le transazioni sono validate ed evase. Il mining rende protetto (da attacchi informatici ndt.) il sistema bitcoin e abilita l emergenza di un consenso su tutta la rete senza il bisogno di un autorità centrale. Il mining è l invenzione che rende bitcoin speciale, un meccanismo di sicurezza che è la base del contante digitale peer-to-peer. La rincompensa per le nuove monete coniate e le fee di transazione sono uno schema di incentivi che allinea le azioni dei miner con la sicurezza della rete, e simultaneamente implementa la fornitura monetaria. In questo capitolo, per iniziare esamineremo il mining come sistema di fornitura monetaria e poi osserveremo la funzione più importante del mining: il meccanismo di consenso decentralizzato emergente che è alla base della sicurezza di bitcoin. L economia di Bitcoin e la Creazione di Valuta I bitcoin sono "coniati"durante la creazione di ogni blocco con un andamento prefissato e in diminuzione. Ogni blocco, generato in una media di 10 minuti, contiene bitcoin completamente nuovi, creati dal niente. Ogni blocchi o approssimativamente ogni quattro anni, il tasso di emissione di moneta è abbassato del 50%. Per i primi quattro anni di vita del network, ogni blocco conteneva 50 nuovi bitcoin. Nel Novembre 2012, il nuovo di tasso di emissione di bitcoin è stato diminuito a 25 bitcoin per blocco e diminuirà ancora a 12.5 bitcoin al blocco , che sarà scoperto in qualche punto del 2016 (circa a settembre ndt.). Il tasso di creazione di nuove monete scende esponenzialmente in questo modo in 64 "dimezzamenti" fino al blocco 13,230,000 (minati approssimativamente nell anno 2137), quando arriverà ad avere il valore minimo di unità di 1 satoshi. Finalmente, dopo milioni di blocchi, approssimativamente nel 2140, circa 2,099,999,997,690,000 satoshi, o circa 21 millioni di bitcoin, saranno stati emessi. In seguito, i blocchi non conterranno più nuovi bitcoin, e i miner saranno ricompensati solamente attraverso le commissioni (fee) di transazione. La riserva monetaria di bitcoin nel tempo basata su di un ritmo di emissione geometricamente decrescente mostra il totale dei bitcoin in circolazione del tempo, e il decrescente andamento d emissione della moneta. 2

184 Figure 1. La riserva monetaria di bitcoin nel tempo basata su di un ritmo di emissione geometricamente decrescente NOTE The maximum number of coins mined is the upper limit of possible mining rewards for bitcoin. In practice, a miner may intentionally mine a block taking less than the full reward. Such blocks have already been mined and more may be mined in the future, resulting in a lower total issuance of the currency. Nel codice di esempio in Uno script per calcolare quanti bitcoin totali saranno emessi, calcoliamo il numero totale di bitcoin che saranno mai emessi. Example 1. Uno script per calcolare quanti bitcoin totali saranno emessi # Original block reward for miners was 50 BTC start_block_reward = 50 # is around every 4 years with a 10 minute block interval reward_interval = def max_money(): # 50 BTC = Satoshis current_reward = 50 * 10**8 total = 0 while current_reward > 0: total += reward_interval * current_reward current_reward /= 2 return total print "Total BTC to ever be created:", max_money(), "Satoshis" 3

185 Eseguendo lo script max_money.py mostra l output prodotto eseguendo questo script. Example 2. Eseguendo lo script max_money.py $ python max_money.py I BTC totali che saranno mai creati: Satoshis The finite and diminishing issuance creates a fixed monetary supply that resists inflation. Unlike a fiat currency, which can be printed in infinite numbers by a central bank, bitcoin can never be inflated by printing. Moneta Deflazionaria La più importante e dibattuta consequenza di una emissione monetaria fissa e in diminuzione è il fatto che la valuta tenderà ad essere intrinsecamente deflazionaria. La deflazione è il fenomeno di apprezzamento di del valore dato da un disaccoppiamento tra la domanda e l offerta che aumenta il valore (e il valore di scambio) di una moneta. L opposto dell inflazione, la deflazione dei prezzi sta a significare che la valuta ha più potenza d acquisto nel tempo. Molti economisti sostengono che un economia deflazionaria è un disastro che dovrebbe essere evitato ad ogni costo. Questo perchè in un periodo di deflazione rapida, le persone tenono a mettere da parte la moneta invece di spenderla, sperando che i prezzi cadranno. Questo fenomeno si è verificato durante il "Decennio Perduto" del Giappone, quando un totale collasso della domanda ha spinto la moneta in una spirale deflativa. Gli esperti di bitcoin sostengono che la deflazione non è in se per se un effetto negativo. Di solito, la deflazione è associata con un collasso di domanda perché quello è l unico esempio di deflazione che usualmente viene studiata. In una valuta fiat con la possibilità di stampare moneta ad libitum, è molto difficile entrare in una spirale deflazionaria a meno che non ci sia un completo collasso nella domanda e la mancanza di volontà di stampare nuova moneta. La deflazione in bitcoin non è causata da un collasso nella domanda ma da una massa monetaria sempre prevedibile. In pratica, è divenuto evidente che l istinto di mettere da parte moneta causato da una valuta deflazionaria potrebbe essere superato tramite sconti dai venditori, fino a che lo scondo superi l istinto di accumulare moneta del compratore. Visto che il venditore è anche lui motivato ad accumulare, lo sconto diviene il prezzo d equilibrio al quale i due istinti di accumulo combaciano. Con sconti del 30% sul prezzo in bitcoin, molti venditori bitcoin non hanno difficoltà contro l istinto di accumulare e generare guadagni. Rimane comunque da vedere il fatto che l aspetto deflazionario della moneta è veramente un problema quando non è spinto da una rapida ritrazione economica. 4

186 Consenso Decentralizzato In the previous chapter we looked at the blockchain, the global public ledger (list) of all transactions, which everyone in the bitcoin network accepts as the authoritative record of ownership. Ma come possono tutti i partecipanti del network concordare su una singola unica "verità" riguardo a chi possiede cosa, senza avere il bisogno di fidarsi di nessuno? Tutti i sistemi di pagamento tradizionale dipendono su di un modello di fiducia che ha un autorità centrale che fornisce il servizio di camera di compensazione (clearing house), praticamente verificando e liquidando tutte le transazioni. Bitcoin non ha un autorità centrale, ma in qualche modo ogni full node ha la copia completa di un libro mastro a cui possa affidarsi usandolo come registro autoritativo. La blockchain non è stata creata da un autorità centrale, tuttavia è assemblata indipendentemente da ogni nodo nella rete. In qualche maniera, ogni nodo del network, agendo sulle informazioni trasmesse attraverso connessioni di rete non sicure, possono arrivare alla stessa conclusione e ad assemblare una copia dello stesso libro mastro come tutti gli altri. Questo capitolo esamina il processo con cui la rete bitcoin ottiene un consenso globale senza aver bisogno di un autorità centrale. Satoshi Nakamoto s main invention is the decentralized mechanism for emergent consensus. Emergent, because consensus is not achieved explicitly there is no election or fixed moment when consensus occurs. Instead, consensus is an emergent artifact of the asynchronous interaction of thousands of independent nodes, all following simple rules. All the properties of bitcoin, including currency, transactions, payments, and the security model that does not depend on central authority or trust, derive from this invention. Il consenso decentralizzato di bitcoin emerge dalla coordinazione di quattro processi che avvengono indipendentemente sui nodi del network: La verifica indipendente di ogni transazione, da ogni full node, basata su una lista comprensiva di criteri Independent aggregation of those transactions into new blocks by mining nodes, coupled with demonstrated computation through a proof-of-work algorithm Independent verification of the new blocks by every node and assembly into a chain Independent selection, by every node, of the chain with the most cumulative computation demonstrated through proof of work In the next few sections we will examine these processes and how they interact to create the emergent property of network-wide consensus that allows any bitcoin node to assemble its own copy of the authoritative, trusted, public, global ledger. Verificazione Indipendente delle Transazioni In [transactions], we saw how wallet software creates transactions by collecting UTXO, providing the appropriate unlocking scripts, and then constructing new outputs assigned to a new owner. The resulting transaction is then sent to the neighboring nodes in the bitcoin network so that it can be 5

187 propagated across the entire bitcoin network. Invece, prima di inoltrare le transazioni ai suoi vicini, ogni nodo bitcoin che riceve una transazione per prima cosa verificherà la transazione. Questo assicura che solo le transazioni valide siano propagate sulla rete, mentre le transazioni non valide saranno scartate al primo nodo che le riceve. Each node verifies every transaction against a long checklist of criteria: La sintassi della transazione e la struttura dati devono essere corrette. Ne la lista degli input ne quella degli output devono essere vuote. La dimensione della transazione in byte è inferiore di MAX_BLOCK_SIZE. I valori di ogni output, come per il totale, devono essere entro il range di valori consentito (meno di 21 milioni di bitcoin, maggiori di zero) Nessuno degli input hanno hash=0, N= 1 (le transazioni coinbase non devono essere trasmesse). nlocktime è inferiore o uguale a INT_MAX. The transaction size in bytes is greater than or equal to 100. The number of signature operations contained in the transaction is less than the signature operation limit. L unlocking script (scriptsig) puo solo aggiungere numeri allo stack, e il locking script (scriptpubkey) deve corrispondere al form isstandard (questo scarta le transazioni "nonstandard"). A matching transaction in the pool, or in a block in the main branch, must exist. For each input, if the referenced output exists in any other transaction in the pool, the transaction must be rejected. For each input, look in the main branch and the transaction pool to find the referenced output transaction. If the output transaction is missing for any input, this will be an orphan transaction. Add to the orphan transactions pool, if a matching transaction is not already in the pool. Per ogni input, se l output di transazione referenziato è un output coinbase, dovrà avere almeno COINBASE_MATURITY (100) conferme. For each input, the referenced output must exist and cannot already be spent. Using the referenced output transactions to get input values, check that each input value, as well as the sum, are in the allowed range of values (less than 21m coins, more than 0). Reject if the sum of input values is less than sum of output values. Reject if transaction fee would be too low to get into an empty block. The unlocking scripts for each input must validate against the corresponding output locking scripts. These conditions can be seen in detail in the functions AcceptToMemoryPool, CheckTransaction, and CheckInputs in the bitcoin reference client. Note that the conditions change over time, to address new types of denial-of-service attacks or sometimes to relax the rules so as to include more types of transactions. 6

188 By independently verifying each transaction as it is received and before propagating it, every node builds a pool of valid (but unconfirmed) transactions known as the transaction pool, memory pool or mempool. Nodi di Mining Some of the nodes on the bitcoin network are specialized nodes called miners. In [ch01_intro_what_is_bitcoin] we introduced Jing, a computer engineering student in Shanghai, China, who is a bitcoin miner. Jing earns bitcoin by running a "mining rig," which is a specialized computerhardware system designed to mine bitcoins. Jing s specialized mining hardware is connected to a server running a full bitcoin node. Unlike Jing, some miners mine without a full node, as we will see in Le Mining Pool. Like every other full node, Jing s node receives and propagates unconfirmed transactions on the bitcoin network. Jing s node, however, also aggregates these transactions into new blocks. Jing s node is listening for new blocks, propagated on the bitcoin network, as do all nodes. However, the arrival of a new block has special significance for a mining node. The competition among miners effectively ends with the propagation of a new block that acts as an announcement of a winner. To miners, receiving a new block means someone else won the competition and they lost. However, the end of one round of a competition is also the beginning of the next round. The new block is not just a checkered flag, marking the end of the race; it is also the starting pistol in the race for the next block. Aggregating Transactions into Blocks After validating transactions, a bitcoin node will add them to the memory pool, or transaction pool, where transactions await until they can be included (mined) into a block. Jing s node collects, validates, and relays new transactions just like any other node. Unlike other nodes, however, Jing s node will then aggregate these transactions into a candidate block. Seguiamo i blocchi che sono stati creati da quando Alice ha comprato un caffè dal Bar di Bob (vedi [cup_of_coffee]). La transazione di Alice è stata inclusa nel blocco Per dimostrare alcuni concetti propri di questo capitolo, assumiamo che quel blocco sia stato minato dal sistema di mining di Jing e abbia seguito la transazione di Alice fino a quando questa non sia divenuta parte di questo nuovo blocco. Jing s mining node maintains a local copy of the blockchain, the list of all blocks created since the beginning of the bitcoin system in By the time Alice buys the cup of coffee, Jing s node has assembled a chain up to block 277,314. Jing s node is listening for transactions, trying to mine a new block and also listening for blocks discovered by other nodes. As Jing s node is mining, it receives block 277,315 through the bitcoin network. The arrival of this block signifies the end of the competition for block 277,315 and the beginning of the competition to create block 277,316. During the previous 10 minutes, while Jing s node was searching for a solution to block 277,315, it was also collecting transactions in preparation for the next block. By now it has collected a few hundred transactions in the memory pool. Upon receiving block 277,315 and validating it, Jing s node will also 7

189 check all the transactions in the memory pool and remove any that were included in block 277,315. Whatever transactions remain in the memory pool are unconfirmed and are waiting to be recorded in a new block. Jing s node immediately constructs a new empty block, a candidate for block 277,316. This block is called a candidate block because it is not yet a valid block, as it does not contain a valid proof of work. The block becomes valid only if the miner succeeds in finding a solution to the proof-of-work algorithm. Età della Transazione, Fee e Priorità To construct the candidate block, Jing s bitcoin node selects transactions from the memory pool by applying a priority metric to each transaction and adding the highest priority transactions first. Transactions are prioritized based on the "age" of the UTXO that is being spent in their inputs, allowing for old and high-value inputs to be prioritized over newer and smaller inputs. Prioritized transactions can be sent without any fees, if there is enough space in the block. La priorità di una transazione è calcolata come la somma del valore e dell età degli input divisi per la dimensione totale della transazione: Priority = Sum (Value of input * Input Age) / Transaction Size --- Priorità = Somma di (Valore dell'input * Età dell'input) / Dimensione della Transazione In questa equazione, il valore di un input è misurato nell unità base, il satoshi (1/100mo di bitcoin). L età di una UTXO è il numero di blocchi che sono "trascorsi" da quando l UTXO è stata registrata nella blockchain, misurando il numero di blocchi di "profondità" dentro la blockchain in cui si trova. La dimensione della transazione è misurata in byte. For a transaction to be considered "high priority," its priority must be greater than 57,600,000, which corresponds to one bitcoin (100m satoshis), aged one day (144 blocks), in a transaction of 250 bytes total size: High Priority > 100,000,000 satoshi * 144 blocchi / 250 byte = 57,600,000 The first 50 kilobytes of transaction space in a block are set aside for high-priority transactions. Jing s node will fill the first 50 kilobytes, prioritizing the highest priority transactions first, regardless of fee. This allows high-priority transactions to be processed even if they carry zero fees. Jing s mining node then fills the rest of the block up to the maximum block size (MAX_BLOCK_SIZE in the code), with transactions that carry at least the minimum fee, prioritizing those with the highest fee per kilobyte of transaction. Se c è uno spazio rimanente nel blocco, il nodo di mining di Jing sceglie di riempirlo con transazioni senza fee. Alcuni miner scelgono di effettuare mining di transazioni senza fee sulla base del minimo 8

190 sforzo. Altri miner potrebbero scegliere di ignorare le transazioni senza fee. Any transactions left in the memory pool, after the block is filled, will remain in the pool for inclusion in the next block. As transactions remain in the memory pool, their inputs "age," as the UTXO they spend get deeper into the blockchain with new blocks added on top. Because a transaction s priority depends on the age of its inputs, transactions remaining in the pool will age and therefore increase in priority. Eventually a transaction without fees might reach a high enough priority to be included in the block for free. Bitcoin transactions do not have an expiration time-out. A transaction that is valid now will be valid in perpetuity. However, if a transaction is only propagated across the network once, it will persist only as long as it is held in a mining node memory pool. When a mining node is restarted, its memory pool is wiped clear, because it is a transient non-persistent form of storage. Although a valid transaction might have been propagated across the network, if it is not executed it may eventually not reside in the memory pool of any miner. Wallet software is expected to retransmit such transactions or reconstruct them with higher fees if they are not successfully executed within a reasonable amount of time. When Jing s node aggregates all the transactions from the memory pool, the new candidate block has 418 transactions with total transaction fees of bitcoin. You can see this block in the blockchain using the Bitcoin Core client command-line interface, as shown in Block 277,316. $ bitcoin-cli getblockhash b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4 $ bitcoin-cli getblock b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4 9

191 Example 3. Block 277,316 { "hash" : " b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4", "confirmations" : 35561, "size" : , "height" : , "version" : 2, "merkleroot" : "c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4cc7cf2e", "tx" : [ "d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f", "b268b45c59b39d b9918caf0ba9d97c56f3b91956ff877c503fbe", more transactions... ], "time" : , "nonce" : , "bits" : "1903a30c", "difficulty" : , "chainwork" : " e92aaf53afa1a", "previousblockhash" : " a7bbd25a417c0374cc e8a9ca74442b01284f0569", "nextblockhash" : " c269dd6ed714dd5db39d36b d78dfd431ba7" } La transazione generatrice The first transaction added to the block is a special transaction, called a generation transaction or coinbase transaction. This transaction is constructed by Jing s node and is his reward for the mining effort. Jing s node creates the generation transaction as a payment to his own wallet: "Pay Jing s address bitcoin." The total amount of reward that Jing collects for mining a block is the sum of the coinbase reward (25 new bitcoins) and the transaction fees ( ) from all the transactions included in the block as shown in Transazione generativa: $ bitcoin-cli getrawtransaction d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f 1 10

192 Example 4. Transazione generativa { "hex" : " ffffffff0f 03443b f fffffffff0110c08d aa970c592640d19de03ff6f 329d6fd2eecb023263b9ba5d1b81c29b523da8b21ac ", "txid" : "d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f", "version" : 1, "locktime" : 0, "vin" : [ { "coinbase" : "03443b f f", "sequence" : } ], "vout" : [ { "value" : , "n" : 0, "scriptpubkey" : { "asm" : "02aa970c592640d19de03ff6f329d6fd2eecb023263b9ba5d1b81c29b523da8b21OP_CHECKSIG", "hex" : "2102aa970c592640d19de03ff6f329d6fd2eecb023263b9ba5d1b81c29b523da8b21ac", "reqsigs" : 1, "type" : "pubkey", "addresses" : [ "1MxTkeEP2PmHSMze5tUZ1hAV3YTKu2Gh1N" ] } } ], "blockhash" : " b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4", "confirmations" : 35566, "time" : , "blocktime" : } Unlike regular transactions, the generation transaction does not consume (spend) UTXO as inputs. Instead, it has only one input, called the coinbase, which creates bitcoin from nothing. The generation transaction has one output, payable to the miner s own bitcoin address. The output of the generation transaction sends the value of bitcoins to the miner s bitcoin address, in this case 1MxTkeEP2PmHSMze5tUZ1hAV3YTKu2Gh1N. 11

193 Ricompensa Coinbase e Fee To construct the generation transaction, Jing s node first calculates the total amount of transaction fees by adding all the inputs and outputs of the 418 transactions that were added to the block. The fees are calculated as: Fee Totali = Somma(Input) - Somma(Output) Nel blocco 277,316, le fee di transazione totali sono di bitcoin. Successivamente, il nodo di Jing calcola la corretta ricompensa per il nuovo blocco. La ricompensa è calcolata tramite la block height, che inizia a 50 bitcoin per blocco ed è ridotta della metà ogni blocchi. Visto che questo blocco è alla height , la ricompensa corretta è di 25 bitcoin. Il calcolo può essere visto in funzione +GetBlockValue+ nel client Bitcoin Core, come mostrato in <<getblockvalue_source>>. Example 5. Calcolando la ricompensa del blocco Funzione GetBlockValue, Client Bitcoin Core, main.cpp, line 1305 int64_t GetBlockValue(int nheight, int64_t nfees) { int64_t nsubsidy = 50 * COIN; int halvings = nheight / Params().SubsidyHalvingInterval(); // Forza la ricompensa del blocco a zero quando il right shift è undefined. if (halvings >= 64) return nfees; // La ricompensa è dimezzata ogni blocchi, questo occorre approssimativamente ogni 4 anni. nsubsidy >>= halvings; } return nsubsidy + nfees; Il sussidio iniziale è calcolato in satoshi moltiplicando 50 con la costante COIN (100,000,000 satoshis). Questo imposta la ricompensa iniziale (nsubsidy) a 5 miliardi di satoshi. Next, the function calculates the number of halvings that have occurred by dividing the current block height by the halving interval (SubsidyHalvingInterval). In the case of block 277,316, with a halving interval every 210,000 blocks, the result is 1 halving. 12

194 Il numero massimo di dimezzamenti consentito è 64, dopo questo il codice impone una ricompensa di zero (ritorna solo le fee) se il 64esimo dimezzamento viene superato. Next, the function uses the binary-right-shift operator to divide the reward (nsubsidy) by two for each round of halving. In the case of block 277,316, this would binary-right-shift the reward of 5 billion satoshis once (one halving) and result in 2.5 billion satoshis, or 25 bitcoins. The binary-right-shift operator is used because it is more efficient for division by two than integer or floating-point division. Infine, la ricompensa coinbase (nsubsidy) è aggiunta alle fee di transazione (nfees), e viene ritornata la somma. La Struttura della Transazione GenerativaStructure of the Generation Transaction Con questi calcoli, il nodo di Jing costruisce la transazione generativa per pagarsi bitcoin. As you can see in Transazione generativa, the generation transaction has a special format. Instead of a transaction input specifying a previous UTXO to spend, it has a "coinbase" input. We examined transaction inputs in [tx_in_structure]. Let s compare a regular transaction input with a generation transaction input. La struttura di un "normale" input di transazione shows the structure of a regular transaction, while La struttura di una transazione di input generativa shows the structure of the generation transaction s input. Table 1. La struttura di un "normale" input di transazione Dimensione Campo Descrizione 32 bytes Hash della Transazione Puntatore alla transazione contenente l UTXO che andrà speso 4 byte Indice dell Output Il numero dell indice della UTXO da spendere, il primo è bytes (VarInt) Dimensione dell Unlocking- Script Lunghezza dell Unlocking-Script in bytes, a seguire Variable Unlocking-Script Uno script che completa le condizioni del locking script dell UTXO. 4 bytes Sequence Number Attualmente disabilitato, funzione di Tx-replacement, impostato a 0xFFFFFFFF Table 2. La struttura di una transazione di input generativa 13

195 Dimensione Campo Descrizione 32 byte Hash di Transazione Tutti i bit sono a zero: Non è un hash di referenza di una transazione 4 byte Indice dell Output Tutti i bit sono uno: 0xFFFFFFFF 1-9 byte (VarInt) Dimensione dei Dati Coinbase Lunghezza dei dati coinbase, da 2 a 100 byte Variabile Dati Coinbase Dati arbitrari usati per nonce extra e per tag di mining Nei blocchi v2, deve iniziare con la block height 4 byte Numero di Sequenza Impostato a 0xFFFFFFFF In a generation transaction, the first two fields are set to values that do not represent a UTXO reference. Instead of a "Transaction Hash," the first field is filled with 32 bytes all set to zero. The "Output Index" is filled with 4 bytes all set to 0xFF (255 decimal). The "Unlocking Script" is replaced by coinbase data, an arbitrary data field used by the miners. Coinbase Data Generation transactions do not have an unlocking script (a.k.a., scriptsig) field. Instead, this field is replaced by coinbase data, which must be between 2 and 100 bytes. Except for the first few bytes, the rest of the coinbase data can be used by miners in any way they want; it is arbitrary data. In the genesis block, for example, Satoshi Nakamoto added the text "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks" in the coinbase data, using it as a proof of the date and to convey a message. Currently, miners use the coinbase data to include extra nonce values and strings identifying the mining pool, as we will see in the following sections. The first few bytes of the coinbase used to be arbitrary, but that is no longer the case. As per Bitcoin Improvement Proposal 34 (BIP0034), version-2 blocks (blocks with the version field set to 2) must contain the block height index as a script "push" operation in the beginning of the coinbase field. In block 277,316 we see that the coinbase (see Transazione generativa), which is in the "Unlocking Script" or scriptsig field of the transaction input, contains the hexadecimal value 03443b f f. Let s decode this value. The first byte, 03, instructs the script execution engine to push the next three bytes onto the script stack (see [tx_script_ops_table_pushdata]). The next three bytes, 0x443b04, are the block height encoded in little-endian format (backward, least significant byte first). Reverse the order of the bytes and the result is 0x043b44, which is 277,316 in decimal. Le poche prossime cifre esadecimali ( ) sono usate per codificare un nonce extra (vedi La Soluzione del Nonce Extra), o valore casuale, usato per trovare una soluzione adatta alla proof of work. 14

196 The final part of the coinbase data (2f f) is the ASCII-encoded string /P2SH/, which indicates that the mining node that mined this block supports the pay-to-script-hash (P2SH) improvement defined in BIP0016. The introduction of the P2SH capability required a "vote" by miners to endorse either BIP0016 or BIP0017. Those endorsing the BIP0016 implementation were to include /P2SH/ in their coinbase data. Those endorsing the BIP0017 implementation of P2SH were to include the string p2sh/chv in their coinbase data. The BIP0016 was elected as the winner, and many miners continued including the string /P2SH/ in their coinbase to indicate support for this feature. Estrae i dati coinbase dal genesis block uses the libbitcoin library introduced in [alt_libraries] to extract the coinbase data from the genesis block, displaying Satoshi s message. Note that the libbitcoin library contains a static copy of the genesis block, so the example code can retrieve the genesis block directly from the library. Example 6. Estrae i dati coinbase dal genesis block /* Display the genesis block message by Satoshi. */ #include <iostream> #include <bitcoin/bitcoin.hpp> int main() { // Create genesis block. bc::block_type block = bc::genesis_block(); // Genesis block contains a single coinbase transaction. assert(block.transactions.size() == 1); // Get first transaction in block (coinbase). const bc::transaction_type& coinbase_tx = block.transactions[0]; // Coinbase tx has a single input. assert(coinbase_tx.inputs.size() == 1); const bc::transaction_input_type& coinbase_input = coinbase_tx.inputs[0]; // Convert the input script to its raw format. const bc::data_chunk& raw_message = save_script(coinbase_input.script); // Convert this to an std::string. std::string message; message.resize(raw_message.size()); std::copy(raw_message.begin(), raw_message.end(), message.begin()); // Display the genesis block message. std::cout << message << std::endl; return 0; } We compile the code with the GNU C++ compiler and run the resulting executable, as shown in Compilando e lanciando il codice di esempio satoshi-words. 15

197 Example 7. Compilando e lanciando il codice di esempio satoshi-words $ # Compila il codice $ g++ -o satoshi-words satoshi-words.cpp $(pkg-config --cflags --libs libbitcoin) $ # Run the executable $./satoshi-words ^D <GS>^A^DEThe Times 03/Jan/2009 Chancellor on brink of second bailout for banks --- Il New York Times - 3 Gennaio Il Cancelliere sull'orlo del secondo salvataggio per le banche Costruendo l Header del Blocco Per costruire il block header, il nodo di mining deve completare sei campi, come mostrato in La struttura di un block header. Table 3. La struttura di un block header Dimensione Campo Descrizione 4 byte Versione Un numero di versione per tracciare upgrade al software e/o al protocollo 32 byte Hash del Blocco Precedente Un riferimento all hash del blocco precedente (genitore) nella chain 32 byte Merkle Root Un hash della radice del merkle tree delle transazioni di questo blocco 4 byte Timestamp Il tempo approssimato della creazione del blocco corrente (secondi dalla Unix Epoch) 4 bytes Target di Difficoltà (Difficulty Target) Il target di difficoltà dell algoritmo di proof-of-work per questo blocco 4 byte Nonce Un contatore utilizzato per l algoritmo di proof-of-work Nel tempo nel quale è stato effettuato mining sul blocco , il numero di versione che descrive la struttura del blocco è 2, che è codificato nel formato little-endian in 4 byte come 0x Next, the mining node needs to add the "Previous Block Hash." That is the hash of the block header of block 277,315, the previous block received from the network, which Jing s node has accepted and selected as the parent of the candidate block 277,316. The block header hash for block 277,315 is: 16

198 a7bbd25a417c0374cc e8a9ca74442b01284f0569 The next step is to summarize all the transactions with a merkle tree, in order to add the merkle root to the block header. The generation transaction is listed as the first transaction in the block. Then, 418 more transactions are added after it, for a total of 419 transactions in the block. As we saw in the [merkle_trees], there must be an even number of "leaf" nodes in the tree, so the last transaction is duplicated, creating 420 nodes, each containing the hash of one transaction. The transaction hashes are then combined, in pairs, creating each level of the tree, until all the transactions are summarized into one node at the "root" of the tree. The root of the merkle tree summarizes all the transactions into a single 32-byte value, which you can see listed as "merkle root" in Block 277,316, and here: c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4cc7cf2e The mining node will then add a 4-byte timestamp, encoded as a Unix "Epoch" timestamp, which is based on the number of seconds elapsed from January 1, 1970, midnight UTC/GMT. The time is equal to Friday, 27 Dec 2013, 23:11:54 UTC/GMT. The node then fills in the difficulty target, which defines the required proof-of-work difficulty to make this a valid block. The difficulty is stored in the block as a "difficulty bits" metric, which is a mantissaexponent encoding of the target. The encoding has a 1-byte exponent, followed by a 3-byte mantissa (coefficient). In block 277,316, for example, the difficulty bits value is 0x1903a30c. The first part 0x19 is a hexadecimal exponent, while the next part, 0x03a30c, is the coefficient. The concept of a difficulty target is explained in Il Target di Difficoltà e Il Retargeting and the "difficulty bits" representation is explained in Rappresentazione della Difficoltà. Il campo finale è il nonce, che è inizializzato a zero. With all the other fields filled, the block header is now complete and the process of mining can begin. The goal is now to find a value for the nonce that results in a block header hash that is less than the difficulty target. The mining node will need to test billions or trillions of nonce values before a nonce is found that satisfies the requirement. Effettuando Mining sul Block Now that a candidate block has been constructed by Jing s node, it is time for Jing s hardware mining rig to "mine" the block, to find a solution to the proof-of-work algorithm that makes the block valid. Throughout this book we have studied cryptographic hash functions as used in various aspects of the bitcoin system. The hash function SHA256 is the function used in bitcoin s mining process. In the simplest terms, mining is the process of hashing the block header repeatedly, changing one parameter, until the resulting hash matches a specific target. The hash function s result cannot be determined in advance, nor can a pattern be created that will produce a specific hash value. This feature of hash functions means that the only way to produce a hash result matching a specific target 17

199 is to try again and again, randomly modifying the input until the desired hash result appears by chance. Algoritmo di Proof-Of-Work A hash algorithm takes an arbitrary-length data input and produces a fixed-length deterministic result, a digital fingerprint of the input. For any specific input, the resulting hash will always be the same and can be easily calculated and verified by anyone implementing the same hash algorithm. The key characteristic of a cryptographic hash algorithm is that it is virtually impossible to find two different inputs that produce the same fingerprint. As a corollary, it is also virtually impossible to select an input in such a way as to produce a desired fingerprint, other than trying random inputs. With SHA256, the output is always 256 bits long, regardless of the size of the input. In Esempio di SHA256, we will use the Python interpreter to calculate the SHA256 hash of the phrase, "I am Satoshi Nakamoto." Example 8. Esempio di SHA256 $ python Python >>> import hashlib >>> print hashlib.sha256("i am Satoshi Nakamoto").hexdigest() 5d7c7ba21cbbcd75d14800b100252d5b428e5b1213d27c385bc141ca6b47989e Esempio di SHA256 shows the result of calculating the hash of "I am Satoshi Nakamoto": 5d7c7ba21cbbcd75d14800b100252d5b428e5b1213d27c385bc141ca6b47989e. This 256-bit number is the hash or digest of the phrase and depends on every part of the phrase. Adding a single letter, punctuation mark, or any other character will produce a different hash. Adesso, se cambiano la frase, dovremo aspettarci hash completamente differenti. Proviamolo aggiungendo un numero alla fine della nostra frase, usando il semplice script python SHA256 Uno script per generare molti hash iterando su di un nonce. 18

200 Example 9. SHA256 Uno script per generare molti hash iterando su di un nonce # example of iterating a nonce in a hashing algorithm's input import hashlib text = "I am Satoshi Nakamoto" # iterate nonce from 0 to 19 for nonce in xrange(20): # add the nonce to the end of the text input = text + str(nonce) # calculate the SHA-256 hash of the input (text+nonce) hash = hashlib.sha256(input).hexdigest() # show the input and hash result print input, '=>', hash Eseguendo questo, verranno prodotti gli hash di varie frasi, ottenute ognuna diversa dall altra tramite l aggiunta di un numero alla fine del testo. Incrementando il numero, possiamo ottenere hash differenti, come mostrato in Output SHA256 di uno script per generare molti hash iterando su di un nonce. 19

201 Example 10. Output SHA256 di uno script per generare molti hash iterando su di un nonce $ python hash_example.py I am Satoshi Nakamoto0 => a80a c8eddee25df36728d I am Satoshi Nakamoto1 => f7bc9a6304a4647bb41241a677b5345f... I am Satoshi Nakamoto2 => ea758a8134b115298a1583ffb80ae I am Satoshi Nakamoto3 => bfa ff072c903d773de30c99bd... I am Satoshi Nakamoto4 => bce8564de9a83c18c31944a66bde992f... I am Satoshi Nakamoto5 => eb362c3cf3479be0a97a e... I am Satoshi Nakamoto6 => 4a2fd48e3be420d0d28e202360cfbaba... I am Satoshi Nakamoto7 => 790b5a1349a5f2b909bf74d0d166b17a... I am Satoshi Nakamoto8 => 702c45e5b15aa54b625d68dd947f I am Satoshi Nakamoto9 => 7007cf7dd40f5e933cd89fff5b791ff0... I am Satoshi Nakamoto10 => c2f38c81992f a21537bd634a... I am Satoshi Nakamoto11 => 7045da6ed8a914690f087690e1e8d66... I am Satoshi Nakamoto12 => 60f01db30c1a0d4cbce2b4b22e88b9b... I am Satoshi Nakamoto13 => 0ebc56d59a34f5082aaef3d66b37a66... I am Satoshi Nakamoto14 => 27ead1ca85da66981fd9da01a8c I am Satoshi Nakamoto15 => fb809c5f83ce97ab554a2812c... I am Satoshi Nakamoto16 => 8fa df33f d I am Satoshi Nakamoto17 => dca9b8b4f8d8e1521fa4eaa46f4f0cd... I am Satoshi Nakamoto18 => 9989a401b2a3a318b01e9ca9a22b0f3... I am Satoshi Nakamoto19 => cda56022ecb5b67b2bc93a2d764e75f... Each phrase produces a completely different hash result. They seem completely random, but you can reproduce the exact results in this example on any computer with Python and see the same exact hashes. The number used as a variable in such a scenario is called a nonce. The nonce is used to vary the output of a cryptographic function, in this case to vary the SHA256 fingerprint of the phrase. To make a challenge out of this algorithm, let s set an arbitrary target: find a phrase that produces a hexadecimal hash that starts with a zero. Fortunately, this isn t difficult! Output SHA256 di uno script per generare molti hash iterando su di un nonce shows that the phrase "I am Satoshi Nakamoto13" produces the hash 0ebc56d59a34f5082aaef3d66b37a661696c2b618e ba a5, which fits our criteria. It took 13 attempts to find it. In terms of probabilities, if the output of the hash function is evenly distributed we would expect to find a result with a 0 as the hexadecimal prefix once every 16 hashes (one out of 16 hexadecimal digits 0 through F). In numerical terms, that means finding a hash value that is less than 0x We call this threshold the target and the goal is to find a hash that is numerically less than the target. If we decrease the target, the task of finding a hash that is less than the target becomes more and more difficult. 20

202 To give a simple analogy, imagine a game where players throw a pair of dice repeatedly, trying to throw less than a specified target. In the first round, the target is 12. Unless you throw double-six, you win. In the next round the target is 11. Players must throw 10 or less to win, again an easy task. Let s say a few rounds later the target is down to 5. Now, more than half the dice throws will add up to more than 5 and therefore be invalid. It takes exponentially more dice throws to win, the lower the target gets. Eventually, when the target is 2 (the minimum possible), only one throw out of every 36, or 2% of them, will produce a winning result. In Output SHA256 di uno script per generare molti hash iterando su di un nonce, the winning "nonce" is 13 and this result can be confirmed by anyone independently. Anyone can add the number 13 as a suffix to the phrase "I am Satoshi Nakamoto" and compute the hash, verifying that it is less than the target. The successful result is also proof of work, because it proves we did the work to find that nonce. While it only takes one hash computation to verify, it took us 13 hash computations to find a nonce that worked. If we had a lower target (higher difficulty) it would take many more hash computations to find a suitable nonce, but only one hash computation for anyone to verify. Furthermore, by knowing the target, anyone can estimate the difficulty using statistics and therefore know how much work was needed to find such a nonce. Bitcoin s proof of work is very similar to the challenge shown in Output SHA256 di uno script per generare molti hash iterando su di un nonce. The miner constructs a candidate block filled with transactions. Next, the miner calculates the hash of this block s header and sees if it is smaller than the current target. If the hash is not less than the target, the miner will modify the nonce (usually just incrementing it by one) and try again. At the current difficulty in the bitcoin network, miners have to try quadrillions of times before finding a nonce that results in a low enough block header hash. A very simplified proof-of-work algorithm is implemented in Python in Implementazione proof-ofwork semplificata. Example 11. Implementazione proof-of-work semplificata #!/usr/bin/env python # example of proof-of-work algorithm import hashlib import time max_nonce = 2 ** 32 # 4 billion def proof_of_work(header, difficulty_bits): # calculate the difficulty target target = 2 ** (256-difficulty_bits) for nonce in xrange(max_nonce): hash_result = hashlib.sha256(str(header)+str(nonce)).hexdigest() 21

203 # check if this is a valid result, below the target if long(hash_result, 16) < target: print "Success with nonce %d" % nonce print "Hash is %s" % hash_result return (hash_result,nonce) print "Failed after %d (max_nonce) tries" % nonce return nonce if name == ' main ': nonce = 0 hash_result = '' # difficulty from 0 to 31 bits for difficulty_bits in xrange(32): difficulty = 2 ** difficulty_bits print "Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits) print "Starting search..." # checkpoint the current time start_time = time.time() # make a new block which includes the hash from the previous block # we fake a block of transactions - just a string new_block = 'test block with transactions' + hash_result # find a valid nonce for the new block (hash_result, nonce) = proof_of_work(new_block, difficulty_bits) # checkpoint how long it took to find a result end_time = time.time() elapsed_time = end_time - start_time print "Elapsed Time: %.4f seconds" % elapsed_time if elapsed_time > 0: # estimate the hashes per second hash_power = float(long(nonce)/elapsed_time) print "Hashing Power: %ld hashes per second" % hash_power Running this code, you can set the desired difficulty (in bits, how many of the leading bits must be 22

204 zero) and see how long it takes for your computer to find a solution. In Eseguendo l esempio di proof of work a varie difficoltà, you can see how it works on an average laptop. Example 12. Eseguendo l esempio di proof of work a varie difficoltà $ python proof-of-work-example.py* Difficulty: 1 (0 bits) --- Difficoltà: 1 (0 bits) [...] Difficulty: 8 (3 bits) --- Difficoltà: 8 (3 bits) Starting search Inizio la ricerca... Success with nonce Trovato con nonce 9 L'hash è 1c1c105e65b47142f028a8f93ddf3dabb bc ce5256cb3c1 Tempo Trascorso: secondi Hashing Power: hashes per second Difficulty: 16 (4 bits) Starting search Inizio la ricerca... Success with nonce 25 Hash is 0f7becfd3bcd1a82e06663c97176add89e7cae0268de46f94e7e11bc3863e148 Elapsed Time: seconds Hashing Power: hashes per second Difficulty: 32 (5 bits) Starting search Inizio la ricerca... Success with nonce 36 Hash is 029ae6e a120630adcbb ab1cf0b94c5189ba8bac1d47e7903 Elapsed Time: seconds Hashing Power: hash per secondo [...] Difficulty: (22 bits) Starting search Inizio la ricerca... Success with nonce Hash is bb8f0e731f0496b8e530da984e85fb3cd2bd81882fe8ba3610b6cefc3 Elapsed Time: seconds Hashing Power: hashes per second Difficulty: (23 bits) Starting search Inizio la ricerca... Success with nonce Hash is cf12dbd20fcba6372a223e098d58786c6ff93488a9f74f5df4df0a3 Tempo Trascorso: secondi Hashing Power: hashes per second Difficulty: (24 bits) 23

205 Starting search Inizio la ricerca... Success with nonce Hash is c3d6b370fccd699708d1b7cb4a b944d68b2acce8b95 Elapsed Time: seconds Hashing Power: hashes per second [...] Difficulty: (26 bits) Starting search Inizio la ricerca... Success with nonce Hash is f0ea21e676b6dde5ad429b9d131a9f2b000802ab2f169cbca22b1e21a Elapsed Time: seconds Hashing Power: hashes per second As you can see, increasing the difficulty by 1 bit causes an exponential increase in the time it takes to find a solution. If you think of the entire 256-bit number space, each time you constrain one more bit to zero, you decrease the search space by half. In Eseguendo l esempio di proof of work a varie difficoltà, it takes 84 million hash attempts to find a nonce that produces a hash with 26 leading bits as zero. Even at a speed of more than 120,000 hashes per second, it still requires 10 minutes on a consumer laptop to find this solution. At the time of writing, the network is attempting to find a block whose header hash is less than c296e6376db3a241271f43fd3f5de7ba18986e517a243baa7. As you can see, there are a lot of zeros at the beginning of that hash, meaning that the acceptable range of hashes is much smaller, hence it s more difficult to find a valid hash. It will take on average more than 150 quadrillion hash calculations per second for the network to discover the next block. That seems like an impossible task, but fortunately the network is bringing 100 petahashes per second (PH/sec) of processing power to bear, which will be able to find a block in about 10 minutes on average. Rappresentazione della Difficoltà In Block 277,316, we saw that the block contains the difficulty target, in a notation called "difficulty bits" or just "bits," which in block 277,316 has the value of 0x1903a30c. This notation expresses the difficulty target as a coefficient/exponent format, with the first two hexadecimal digits for the exponent and the next six hex digits as the coefficient. In this block, therefore, the exponent is 0x19 and the coefficient is 0x03a30c. La formula per calcolare il target di difficoltà da questa rappresentazione è: target = coefficient * 2^(8 * (exponent 3)) Usando quella formula, e i bit di difficoltà con valore 0x1903a30c, otteniamo: 24

206 target = 0x03a30c * 2^(0x08 * (0x19-0x03))^ => target = 0x03a30c * 2^(0x08 * 0x16)^ => target = 0x03a30c * 2^0xB0^ il quale decimale è: => target = 238,348 * 2^176^ => target = 22,829,202,948,393,929,850,749,706,076,701,368,331,072,452,018,388,575,715,328 ri-convertendolo in esadecimale: => target = 0x A30C This means that a valid block for height 277,316 is one that has a block header hash that is less than the target. In binary that number would have more than the first 60 bits set to zero. With this level of difficulty, a single miner processing 1 trillion hashes per second (1 tera-hash per second or 1 TH/sec) would only find a solution once every 8,496 blocks or once every 59 days, on average. Il Target di Difficoltà e Il Retargeting As we saw, the target determines the difficulty and therefore affects how long it takes to find a solution to the proof-of-work algorithm. This leads to the obvious questions: Why is the difficulty adjustable, who adjusts it, and how? Bitcoin s blocks are generated every 10 minutes, on average. This is bitcoin s heartbeat and underpins the frequency of currency issuance and the speed of transaction settlement. It has to remain constant not just over the short term, but over a period of many decades. Over this time, it is expected that computer power will continue to increase at a rapid pace. Furthermore, the number of participants in mining and the computers they use will also constantly change. To keep the block generation time at 10 minutes, the difficulty of mining must be adjusted to account for these changes. In fact, difficulty is a dynamic parameter that will be periodically adjusted to meet a 10-minute block target. In simple terms, the difficulty target is set to whatever mining power will result in a 10-minute block interval. How, then, is such an adjustment made in a completely decentralized network? Difficulty retargeting occurs automatically and on every full node independently. Every 2,016 blocks, all nodes retarget the proof-of-work difficulty. The equation for retargeting difficulty measures the time it took to find the last 2,016 blocks and compares that to the expected time of 20,160 minutes (two weeks based upon a desired 10-minute block time). The ratio between the actual timespan and desired timespan is calculated and a corresponding adjustment (up or down) is made to the difficulty. In simple terms: If 25

207 the network is finding blocks faster than every 10 minutes, the difficulty increases. If block discovery is slower than expected, the difficulty decreases. L equazione può essere riassunta in: New Difficulty = Old Difficulty * (Tempo degli ultimi 2016 Blocchi / minuti) Ritargettizzando la difficoltà di proof-of-work GetNextWorkRequired() in pow.cpp, linea 43 mostra il codice utilizzato nel client Bitcoin Core. Example 13. Ritargettizzando la difficoltà di proof-of-work GetNextWorkRequired() in pow.cpp, linea 43 // Torna indietro a quello che volevamo essere 14 giorni di blocchi const CBlockIndex* pindexfirst = pindexlast; for (int i = 0; pindexfirst && i < Params().Interval()-1; i++) pindexfirst = pindexfirst->pprev; assert(pindexfirst); // Step di aggiustamento del limitelimit adjustment step int64_t nactualtimespan = pindexlast->getblocktime() - pindexfirst->getblocktime(); LogPrintf(" nactualtimespan = %d before bounds\n", nactualtimespan); if (nactualtimespan < Params().TargetTimespan()/4) nactualtimespan = Params().TargetTimespan()/4; if (nactualtimespan > Params().TargetTimespan()*4) nactualtimespan = Params().TargetTimespan()*4; // Retarget uint256 bnnew; uint256 bnold; bnnew.setcompact(pindexlast->nbits); bnold = bnnew; bnnew *= nactualtimespan; bnnew /= Params().TargetTimespan(); if (bnnew > Params().ProofOfWorkLimit()) bnnew = Params().ProofOfWorkLimit(); NOTE While the difficulty calibration happens every 2,016 blocks, because of an off-by-one error in the original Bitcoin Core client it is based on the total time of the previous 2,015 blocks (not 2,016 as it should be), resulting in a retargeting bias towards higher difficulty by 0.05%. The parameters Interval (2,016 blocks) and TargetTimespan (two weeks as 1,209,600 seconds) are 26

208 defined in chainparams.cpp. To avoid extreme volatility in the difficulty, the retargeting adjustment must be less than a factor of four (4) per cycle. If the required difficulty adjustment is greater than a factor of four, it will be adjusted by the maximum and not more. Any further adjustment will be accomplished in the next retargeting period because the imbalance will persist through the next 2,016 blocks. Therefore, large discrepancies between hashing power and difficulty might take several 2,016 block cycles to balance out. TIP La difficoltà nel trovare un blocco bitcoin è approssivativamente '10 minuti di calcolo' per l intero network, basato sul tempo che ci vuole per trovare i precedenti blocchi, aggiustata ogni blocchi. Note that the target difficulty is independent of the number of transactions or the value of transactions. This means that the amount of hashing power and therefore electricity expended to secure bitcoin is also entirely independent of the number of transactions. Bitcoin can scale up, achieve broader adoption, and remain secure without any increase in hashing power from today s level. The increase in hashing power represents market forces as new miners enter the market to compete for the reward. As long as enough hashing power is under the control of miners acting honestly in pursuit of the reward, it is enough to prevent "takeover" attacks and, therefore, it is enough to secure bitcoin. The target difficulty is closely related to the cost of electricity and the exchange rate of bitcoin vis-a-vis the currency used to pay for electricity. High-performance mining systems are about as efficient as possible with the current generation of silicon fabrication, converting electricity into hashing computation at the highest rate possible. The primary influence on the mining market is the price of one kilowatt-hour in bitcoin, because that determines the profitability of mining and therefore the incentives to enter or exit the mining market. Effettuando Mining del Blocco con Successo As we saw earlier, Jing s node has constructed a candidate block and prepared it for mining. Jing has several hardware mining rigs with application-specific integrated circuits, where hundreds of thousands of integrated circuits run the SHA256 algorithm in parallel at incredible speeds. These specialized machines are connected to his mining node over USB. Next, the mining node running on Jing s desktop transmits the block header to his mining hardware, which starts testing trillions of nonces per second. Almost 11 minutes after starting to mine block 277,316, one of the hardware mining machines finds a solution and sends it back to the mining node. When inserted into the block header, the nonce 4,215,469,401 produces a block hash of: a7bbd25a417c0374cc e8a9ca74442b01284f0569 che è inferiore al target: 27

209 A30C Immediately, Jing s mining node transmits the block to all its peers. They receive, validate, and then propagate the new block. As the block ripples out across the network, each node adds it to its own copy of the blockchain, extending it to a new height of 277,316 blocks. As mining nodes receive and validate the block, they abandon their efforts to find a block at the same height and immediately start computing the next block in the chain. Nella prossima sezione, osserveremo al processo usato da ogni nodo per validare un blocco e selezionare la catena più lunga, creando il consenso che forma la blockchain decentralizzata. Validando un Nuovo Blocco The third step in bitcoin s consensus mechanism is independent validation of each new block by every node on the network. As the newly solved block moves across the network, each node performs a series of tests to validate it before propagating it to its peers. This ensures that only valid blocks are propagated on the network. The independent validation also ensures that miners who act honestly get their blocks incorporated in the blockchain, thus earning the reward. Those miners who act dishonestly have their blocks rejected and not only lose the reward, but also waste the effort expended to find a proof-of-work solution, thus incurring the cost of electricity without compensation. When a node receives a new block, it will validate the block by checking it against a long list of criteria that must all be met; otherwise, the block is rejected. These criteria can be seen in the Bitcoin Core client in the functions CheckBlock and CheckBlockHeader and include: La struttura del blocco è sintatticamente valida L hash del block header è inferiore della difficoltà del target (impone la proof of work) Il timestamp del blocco è inferiore di due ore nel futuro (permettendo errori temporali) *La dimensione del blocco è entro i limiti accettati La prima transazione (e solo la prima) è una transazione di generazione coinbase Tutte le transazioni nel blocco sono valide usando la checklist di transazione introdotta in Verificazione Indipendente delle Transazioni The independent validation of each new block by every node on the network ensures that the miners can t cheat. In previous sections we saw how the miners get to write a transaction that awards them the new bitcoins created within the block and claim the transaction fees. Why don t miners write themselves a transaction for a thousand bitcoin instead of the correct reward? Because every node validates blocks according to the same rules. An invalid coinbase transaction would make the entire block invalid, which would result in the block being rejected and, therefore, that transaction would never become part of the ledger. The miners have to construct a perfect block, based on the shared rules that all nodes follow, and mine it with a correct solution to the proof of work. To do so, they expend a lot of electricity in mining, and if they cheat, all the electricity and effort is wasted. This is 28

210 why independent validation is a key component of decentralized consensus. Assemblando e Selezionando Catene di Blocchi The final step in bitcoin s decentralized consensus mechanism is the assembly of blocks into chains and the selection of the chain with the most proof of work. Once a node has validated a new block, it will then attempt to assemble a chain by connecting the block to the existing blockchain. I nodi mantengono tre tipi di blocchi: quelli connessi alla blockchain principale, quelli che formano rami che partono dalla blockchain principale (chain secondarie), ed infine, blocchi che non hanno un genitore presente nelle chain conosciute (orfani). I blocco non validi sono rifiutato non appena uno dei criteri di validazione fallisce e quindi non vengono inclusi in nessuna chain. The "main chain" at any time is whichever chain of blocks has the most cumulative difficulty associated with it. Under most circumstances this is also the chain with the most blocks in it, unless there are two equal-length chains and one has more proof of work. The main chain will also have branches with blocks that are "siblings" to the blocks on the main chain. These blocks are valid but not part of the main chain. They are kept for future reference, in case one of those chains is extended to exceed the main chain in difficulty. In the next section (I Fork della Blockchain), we will see how secondary chains occur as a result of an almost simultaneous mining of blocks at the same height. When a new block is received, a node will try to slot it into the existing blockchain. The node will look at the block s "previous block hash" field, which is the reference to the new block s parent. Then, the node will attempt to find that parent in the existing blockchain. Most of the time, the parent will be the "tip" of the main chain, meaning this new block extends the main chain. For example, the new block 277,316 has a reference to the hash of its parent block 277,315. Most nodes that receive 277,316 will already have block 277,315 as the tip of their main chain and will therefore link the new block and extend that chain. Sometimes, as we will see in I Fork della Blockchain, the new block extends a chain that is not the main chain. In that case, the node will attach the new block to the secondary chain it extends and then compare the difficulty of the secondary chain to the main chain. If the secondary chain has more cumulative difficulty than the main chain, the node will reconverge on the secondary chain, meaning it will select the secondary chain as its new main chain, making the old main chain a secondary chain. If the node is a miner, it will now construct a block extending this new, longer, chain. If a valid block is received and no parent is found in the existing chains, that block is considered an "orphan." Orphan blocks are saved in the orphan block pool where they will stay until their parent is received. Once the parent is received and linked into the existing chains, the orphan can be pulled out of the orphan pool and linked to the parent, making it part of a chain. Orphan blocks usually occur when two blocks that were mined within a short time of each other are received in reverse order (child before parent). By selecting the greatest-difficulty chain, all nodes eventually achieve network-wide consensus. Temporary discrepancies between chains are resolved eventually as more proof of work is added, extending one of the possible chains. Mining nodes "vote" with their mining power by choosing which 29

211 chain to extend by mining the next block. When they mine a new block and extend the chain, the new block itself represents their vote. In the next section we will look at how discrepancies between competing chains (forks) are resolved by the independent selection of the longest difficulty chain. I Fork della Blockchain Visto che la blockchain è una struttura dati decentralizzata, le diverse copie di essa non sono sempre identiche. I blocchi potrebbero arrivare ai vari nodi in momenti differenti, questo fa si che i nodi abbiano diverse prospettive della blockchain. Per risolvere questo problema, ogni nodo seleziona e cerca di estendere sempre la catena dei blocchi che rappresenta la maggiore proof-of-work, conosciuta anche come la longest chain (la catena più lunga) o la catena piu grande e con difficoltà cumulativa più alta. Sommando la difficoltà registrata in ogni blocco in una chain, un nodo può calcolare la quantità totale di proof-of-work che è stata spesa per creare quella chain. Fino a quando tutti i nodi selezionano la catena con difficoltà cumulativa più lunga, la rete globale bitcoin eventualmente convergerà verso uno stato consistente. Le ramificazioni (fork) avvengono come inconsistenze temporanee tra le varie versioni della blockchain, che sono risolte da eventuali riconvergenze mano a mano che più blocchi sono aggiunti a uno dei rami. In the next few diagrams, we follow the progress of a "fork" event across the network. The diagram is a simplified representation of bitcoin as a global network. In reality, the bitcoin network s topology is not organized geographically. Rather, it forms a mesh network of interconnected nodes, which might be located very far from each other geographically. The representation of a geographic topology is a simplification used for the purposes of illustrating a fork. In the real bitcoin network, the "distance" between nodes is measured in "hops" from node to node, not on their physical location. For illustration purposes, different blocks are shown as different colors, spreading across the network and coloring the connections they traverse. Nel primo diagramma (Visualizzazione di un evento di fork di blockchain prima del fork), il network ha una prospettiva unificata della blockchain, con il blocco blu come estremità della chain principale. 30

212 Figure 2. Visualizzazione di un evento di fork di blockchain prima del fork A "fork" occurs whenever there are two candidate blocks competing to form the longest blockchain. This occurs under normal conditions whenever two miners solve the proof-of-work algorithm within a short period of time from each other. As both miners discover a solution for their respective candidate blocks, they immediately broadcast their own "winning" block to their immediate neighbors who begin propagating the block across the network. Each node that receives a valid block will incorporate it into its blockchain, extending the blockchain by one block. If that node later sees another candidate block extending the same parent, it connects the second candidate on a secondary chain. As a result, some nodes will "see" one candidate block first, while other nodes will see the other candidate block and two competing versions of the blockchain will emerge. In Visualizzazione di un evento di fork di blockchain: due blocchi trovati simultaneamente, we see two miners who mine two different blocks almost simultaneously. Both of these blocks are children of the blue block, meant to extend the chain by building on top of the blue block. To help us track it, one is visualized as a red block originating from Canada, and the other is marked as a green block originating from Australia. Let s assume, for example, that a miner in Canada finds a proof-of-work solution for a block "red" that extends the blockchain, building on top of the parent block "blue." Almost simultaneously, an Australian miner who was also extending block "blue" finds a solution for block "green," his candidate block. Now, there are two possible blocks, one we call "red," originating in Canada, and one we call "green," originating in Australia. Both blocks are valid, both blocks contain a valid solution to the proof of work, and both blocks extend the same parent. Both blocks likely contain most of the same transactions, with only perhaps a few differences in the order of transactions. 31

213 Figure 3. Visualizzazione di un evento di fork di blockchain: due blocchi trovati simultaneamente As the two blocks propagate, some nodes receive block "red" first and some receive block "green" first. As shown in Visualizzazione di un evento di fork di blockchain: due blocchi propagati, dividendo il network, the network splits into two different perspectives of the blockchain, one side topped with a red block, the other with a green block. Figure 4. Visualizzazione di un evento di fork di blockchain: due blocchi propagati, dividendo il network From that moment, the bitcoin network nodes closest (topologically, not geographically) to the Canadian node will hear about block "red" first and will create a new greatest-cumulative-difficulty blockchain with "red" as the last block in the chain (e.g., blue-red), ignoring the candidate block "green" 32

214 that arrives a bit later. Meanwhile, nodes closer to the Australian node will take that block as the winner and extend the blockchain with "green" as the last block (e.g., blue-green), ignoring "red" when it arrives a few seconds later. Any miners that saw "red" first will immediately build candidate blocks that reference "red" as the parent and start trying to solve the proof of work for these candidate blocks. The miners that accepted "green" instead will start building on top of "green" and extending that chain. Forks are almost always resolved within one block. As part of the network s hashing power is dedicated to building on top of "red" as the parent, another part of the hashing power is focused on building on top of "green." Even if the hashing power is almost evenly split, it is likely that one set of miners will find a solution and propagate it before the other set of miners have found any solutions. Let s say, for example, that the miners building on top of "green" find a new block "pink" that extends the chain (e.g., blue-green-pink). They immediately propagate this new block and the entire network sees it as a valid solution as shown in Visualizzazione di un evento di fork di blockchain: un nuovo blocco estende un fork. Figure 5. Visualizzazione di un evento di fork di blockchain: un nuovo blocco estende un fork All nodes that had chosen "green" as the winner in the previous round will simply extend the chain one more block. The nodes that chose "red" as the winner, however, will now see two chains: bluegreen-pink and blue-red. The chain blue-green-pink is now longer (more cumulative difficulty) than the chain blue-red. As a result, those nodes will set the chain blue-green-pink as main chain and change the blue-red chain to being a secondary chain, as shown in Visualizzazione di un evento di fork di blockchain: il network riconverge su di una nuova longest chain. This is a chain reconvergence, because those nodes are forced to revise their view of the blockchain to incorporate the new evidence of a longer chain. Any miners working on extending the chain blue-red will now stop that work because their candidate block is an "orphan," as its parent "red" is no longer on the longest chain. The transactions within "red" are queued up again for processing in the next block, because that block is no longer in the main chain. The entire network re-converges on a single blockchain blue-green-pink, 33

215 with "pink" as the last block in the chain. All miners immediately start working on candidate blocks that reference "pink" as their parent to extend the blue-green-pink chain. Figure 6. Visualizzazione di un evento di fork di blockchain: il network riconverge su di una nuova longest chain It is theoretically possible for a fork to extend to two blocks, if two blocks are found almost simultaneously by miners on opposite "sides" of a previous fork. However, the chance of that happening is very low. Whereas a one-block fork might occur every week, a two-block fork is exceedingly rare. Bitcoin s block interval of 10 minutes is a design compromise between fast confirmation times (settlement of transactions) and the probability of a fork. A faster block time would make transactions clear faster but lead to more frequent blockchain forks, whereas a slower block time would decrease the number of forks but make settlement slower. Il Mining e la Gara di Hashing Bitcoin mining is an extremely competitive industry. The hashing power has increased exponentially every year of bitcoin s existence. Some years the growth has reflected a complete change of technology, such as in 2010 and 2011 when many miners switched from using CPU mining to GPU mining and field programmable gate array (FPGA) mining. In 2013 the introduction of ASIC mining lead to another giant leap in mining power, by placing the SHA256 function directly on silicon chips specialized for the purpose of mining. The first such chips could deliver more mining power in a single box than the entire bitcoin network in La lista seguente mostra la potenza totale di hashing del network bitcoin, durante i primi cinque anni di operatività: 34

216 MH/sec 8 MH/sec (16 crescita) MH/sec 116 GH/sec (14,500 di crescita) GH/sec 9 TH/sec (562 di crescita) TH/sec 23 TH/sec (2.5 di crescita) TH/sec 10 PH/sec (450 di crescita) PH/sec 150 PH/sec in August (15 di crescita) In the chart in Potenza di hashing totale, gigahash per secondo, nel corso di due anni, we see the bitcoin network s hashing power increase over the past two years. As you can see, the competition between miners and the growth of bitcoin has resulted in an exponential increase in the hashing power (total hashes per second across the network). Figure 7. Potenza di hashing totale, gigahash per secondo, nel corso di due anni As the amount of hashing power applied to mining bitcoin has exploded, the difficulty has risen to match it. The difficulty metric in the chart shown in La metrica di difficoltà di mining di Bitcoin, in due anni is measured as a ratio of current difficulty over minimum difficulty (the difficulty of the first block). 35

217 Figure 8. La metrica di difficoltà di mining di Bitcoin, in due anni In the last two years, the ASIC mining chips have become increasingly denser, approaching the cutting edge of silicon fabrication with a feature size (resolution) of 22 nanometers (nm). Currently, ASIC manufacturers are aiming to overtake general-purpose CPU chip manufacturers, designing chips with a feature size of 16nm, because the profitability of mining is driving this industry even faster than general computing. There are no more giant leaps left in bitcoin mining, because the industry has reached the forefront of Moore s Law, which stipulates that computing density will double approximately every 18 months. Still, the mining power of the network continues to advance at an exponential pace as the race for higher density chips is matched with a race for higher density data centers where thousands of these chips can be deployed. It s no longer about how much mining can be done with one chip, but how many chips can be squeezed into a building, while still dissipating the heat and providing adequate power. La Soluzione del Nonce Extra Since 2012, bitcoin mining has evolved to resolve a fundamental limitation in the structure of the block header. In the early days of bitcoin, a miner could find a block by iterating through the nonce until the resulting hash was below the target. As difficulty increased, miners often cycled through all 4 billion values of the nonce without finding a block. However, this was easily resolved by updating the block timestamp to account for the elapsed time. Because the timestamp is part of the header, the change would allow miners to iterate through the values of the nonce again with different results. Once mining hardware exceeded 4 GH/sec, however, this approach became increasingly difficult because the nonce values were exhausted in less than a second. As ASIC mining equipment started pushing and then exceeding the TH/sec hash rate, the mining software needed more space for nonce values in order to find valid blocks. The timestamp could be stretched a bit, but moving it too far into the future would cause the block to become invalid. A new source of "change" was needed in the block header. The solution was to use the coinbase transaction as a source of extra nonce values. Because the coinbase script can store between 2 and 100 bytes of data, miners started using that space as extra nonce space, allowing them to explore a much larger range of block header values to find valid blocks. The coinbase transaction is included in the merkle tree, which means that any change in the coinbase script causes 36

218 the merkle root to change. Eight bytes of extra nonce, plus the 4 bytes of "standard" nonce allow miners to explore a total 2 96 (8 followed by 28 zeros) possibilities per second without having to modify the timestamp. If, in the future, miners could run through all these possibilities, they could then modify the timestamp. There is also more space in the coinbase script for future expansion of the extra nonce space. Le Mining Pool In this highly competitive environment, individual miners working alone (also known as solo miners) don t stand a chance. The likelihood of them finding a block to offset their electricity and hardware costs is so low that it represents a gamble, like playing the lottery. Even the fastest consumer ASIC mining system cannot keep up with commercial systems that stack tens of thousands of these chips in giant warehouses near hydro-electric power stations. Miners now collaborate to form mining pools, pooling their hashing power and sharing the reward among thousands of participants. By participating in a pool, miners get a smaller share of the overall reward, but typically get rewarded every day, reducing uncertainty. Let s look at a specific example. Assume a miner has purchased mining hardware with a combined hashing rate of 6,000 gigahashes per second (GH/s), or 6 TH/s. In August of 2014 this equipment costs approximately $10,000. The hardware consumes 3 kilowatts (kw) of electricity when running, 72 kwhours a day, at a cost of $7 or $8 per day on average. At current bitcoin difficulty, the miner will be able to solo mine a block approximately once every 155 days, or every 5 months. If the miner does find a single block in that timeframe, the payout of 25 bitcoins, at approximately $600 per bitcoin, will result in a single payout of $15,000, which will cover the entire cost of the hardware and the electricity consumed over the time period, leaving a net profit of approximately $3,000. However, the chance of finding a block in a five-month period depends on the miner s luck. He might find two blocks in five months and make a very large profit. Or he might not find a block for 10 months and suffer a financial loss. Even worse, the difficulty of the bitcoin proof-of-work algorithm is likely to go up significantly over that period, at the current rate of growth of hashing power, meaning the miner has, at most, six months to break even before the hardware is effectively obsolete and must be replaced by more powerful mining hardware. If this miner participates in a mining pool, instead of waiting for a once-infive-months $15,000 windfall, he will be able to earn approximately $500 to $750 per week. The regular payouts from a mining pool will help him amortize the cost of hardware and electricity over time without taking an enormous risk. The hardware will still be obsolete in six to nine months and the risk is still high, but the revenue is at least regular and reliable over that period. Mining pools coordinate many hundreds or thousands of miners, over specialized pool-mining protocols. The individual miners configure their mining equipment to connect to a pool server, after creating an account with the pool. Their mining hardware remains connected to the pool server while mining, synchronizing their efforts with the other miners. Thus, the pool miners share the effort to mine a block and then share in the rewards. Successful blocks pay the reward to a pool bitcoin address, rather than individual miners. The pool server will periodically make payments to the miners' bitcoin addresses, once their share of the rewards has reached a certain threshold. Typically, the pool server charges a percentage fee of the 37

219 rewards for providing the pool-mining service. Miners participating in a pool split the work of searching for a solution to a candidate block, earning "shares" for their mining contribution. The mining pool sets a lower difficulty target for earning a share, typically more than 1,000 times easier than the bitcoin network s difficulty. When someone in the pool successfully mines a block, the reward is earned by the pool and then shared with all miners in proportion to the number of shares they contributed to the effort. Pools are open to any miner, big or small, professional or amateur. A pool will therefore have some participants with a single small mining machine, and others with a garage full of high-end mining hardware. Some will be mining with a few tens of a kilowatt of electricity, others will be running a data center consuming a megawatt of power. How does a mining pool measure the individual contributions, so as to fairly distribute the rewards, without the possibility of cheating? The answer is to use bitcoin s proof-of-work algorithm to measure each pool miner s contribution, but set at a lower difficulty so that even the smallest pool miners win a share frequently enough to make it worthwhile to contribute to the pool. By setting a lower difficulty for earning shares, the pool measures the amount of work done by each miner. Each time a pool miner finds a block header hash that is less than the pool difficulty, she proves she has done the hashing work to find that result. More importantly, the work to find shares contributes, in a statistically measurable way, to the overall effort to find a hash lower than the bitcoin network s target. Thousands of miners trying to find low-value hashes will eventually find one low enough to satisfy the bitcoin network target. Let s return to the analogy of a dice game. If the dice players are throwing dice with a goal of throwing less than four (the overall network difficulty), a pool would set an easier target, counting how many times the pool players managed to throw less than eight. When pool players throw less than eight (the pool share target), they earn shares, but they don t win the game because they don t achieve the game target (less than four). The pool players will achieve the easier pool target much more often, earning them shares very regularly, even when they don t achieve the harder target of winning the game. Every now and then, one of the pool players will throw a combined dice throw of less than four and the pool wins. Then, the earnings can be distributed to the pool players based on the shares they earned. Even though the target of eight-or-less wasn t winning, it was a fair way to measure dice throws for the players, and it occasionally produces a less-than-four throw. Similarly, a mining pool will set a pool difficulty that will ensure that an individual pool miner can find block header hashes that are less than the pool difficulty quite often, earning shares. Every now and then, one of these attempts will produce a block header hash that is less than the bitcoin network target, making it a valid block and the whole pool wins. Le Pool Gestite Most mining pools are "managed," meaning that there is a company or individual running a pool server. The owner of the pool server is called the pool operator, and he charges pool miners a percentage fee of the earnings. The pool server runs specialized software and a pool-mining protocol that coordinates the activities of the pool miners. The pool server is also connected to one or more full bitcoin nodes and has direct 38

220 access to a full copy of the blockchain database. This allows the pool server to validate blocks and transactions on behalf of the pool miners, relieving them of the burden of running a full node. For pool miners, this is an important consideration, because a full node requires a dedicated computer with at least 15 to 20 GB of persistent storage (disk) and at least 2 GB of memory (RAM). Furthermore, the bitcoin software running on the full node needs to be monitored, maintained, and upgraded frequently. Any downtime caused by a lack of maintenance or lack of resources will hurt the miner s profitability. For many miners, the ability to mine without running a full node is another big benefit of joining a managed pool. Pool miners connect to the pool server using a mining protocol such as Stratum (STM) or GetBlockTemplate (GBT). An older standard called GetWork (GWK) has been mostly obsolete since late 2012, because it does not easily support mining at hash rates above 4 GH/s. Both the STM and GBT protocols create block templates that contain a template of a candidate block header. The pool server constructs a candidate block by aggregating transactions, adding a coinbase transaction (with extra nonce space), calculating the merkle root, and linking to the previous block hash. The header of the candidate block is then sent to each of the pool miners as a template. Each pool miner then mines using the block template, at a lower difficulty than the bitcoin network difficulty, and sends any successful results back to the pool server to earn shares. P2Pool Managed pools create the possibility of cheating by the pool operator, who might direct the pool effort to double-spend transactions or invalidate blocks (see Attacchi al Consenso). Furthermore, centralized pool servers represent a single-point-of-failure. If the pool server is down or is slowed by a denial-ofservice attack, the pool miners cannot mine. In 2011, to resolve these issues of centralization, a new pool mining method was proposed and implemented: P2Pool is a peer-to-peer mining pool, without a central operator. P2Pool works by decentralizing the functions of the pool server, implementing a parallel blockchainlike system called a share chain. A share chain is a blockchain running at a lower difficulty than the bitcoin blockchain. The share chain allows pool miners to collaborate in a decentralized pool, by mining shares on the share chain at a rate of one share block every 30 seconds. Each of the blocks on the share chain records a proportionate share reward for the pool miners who contribute work, carrying the shares forward from the previous share block. When one of the share blocks also achieves the difficulty target of the bitcoin network, it is propagated and included on the bitcoin blockchain, rewarding all the pool miners who contributed to all the shares that preceded the winning share block. Essentially, instead of a pool server keeping track of pool miner shares and rewards, the share chain allows all pool miners to keep track of all shares using a decentralized consensus mechanism like bitcoin s blockchain consensus mechanism. P2Pool mining is more complex than pool mining because it requires that the pool miners run a dedicated computer with enough disk space, memory, and Internet bandwidth to support a full bitcoin node and the P2Pool node software. P2Pool miners connect their mining hardware to their local P2Pool node, which simulates the functions of a pool server by sending block templates to the mining hardware. On P2Pool, individual pool miners construct their own candidate blocks, aggregating transactions much like solo miners, but then mine collaboratively on the share chain. P2Pool is a 39

221 hybrid approach that has the advantage of much more granular payouts than solo mining, but without giving too much control to a pool operator like managed pools. Recently, participation in P2Pool has increased significantly as mining concentration in mining pools has approached levels that create concerns of a 51% attack (see Attacchi al Consenso). Further development of the P2Pool protocol continues with the expectation of removing the need for running a full node and therefore making decentralized mining even easier to use. Even though P2Pool reduces the concentration of power by mining pool operators, it is conceivably vulnerable to 51% attacks against the share chain itself. A much broader adoption of P2Pool does not solve the 51% attack problem for bitcoin itself. Rather, P2Pool makes bitcoin more robust overall, as part of a diversified mining ecosystem. Attacchi al Consenso Bitcoin s consensus mechanism is, at least theoretically, vulnerable to attack by miners (or pools) that attempt to use their hashing power to dishonest or destructive ends. As we saw, the consensus mechanism depends on having a majority of the miners acting honestly out of self-interest. However, if a miner or group of miners can achieve a significant share of the mining power, they can attack the consensus mechanism so as to disrupt the security and availability of the bitcoin network. It is important to note that consensus attacks can only affect future consensus, or at best the most recent past (tens of blocks). Bitcoin s ledger becomes more and more immutable as time passes. While in theory, a fork can be achieved at any depth, in practice, the computing power needed to force a very deep fork is immense, making old blocks practically immutable. Consensus attacks also do not affect the security of the private keys and signing algorithm (ECDSA). A consensus attack cannot steal bitcoins, spend bitcoins without signatures, redirect bitcoins, or otherwise change past transactions or ownership records. Consensus attacks can only affect the most recent blocks and cause denial-ofservice disruptions on the creation of future blocks. One attack scenario against the consensus mechanism is called the "51% attack." In this scenario a group of miners, controlling a majority (51%) of the total network s hashing power, collude to attack bitcoin. With the ability to mine the majority of the blocks, the attacking miners can cause deliberate "forks" in the blockchain and double-spend transactions or execute denial-of-service attacks against specific transactions or addresses. A fork/double-spend attack is one where the attacker causes previously confirmed blocks to be invalidated by forking below them and re-converging on an alternate chain. With sufficient power, an attacker can invalidate six or more blocks in a row, causing transactions that were considered immutable (six confirmations) to be invalidated. Note that a doublespend can only be done on the attacker s own transactions, for which the attacker can produce a valid signature. Double-spending one s own transactions is profitable if by invalidating a transaction the attacker can get a nonreversible exchange payment or product without paying for it. Let s examine a practical example of a 51% attack. In the first chapter, we looked at a transaction between Alice and Bob for a cup of coffee. Bob, the cafe owner, is willing to accept payment for cups of coffee without waiting for confirmation (mining in a block), because the risk of a double-spend on a 40

222 cup of coffee is low in comparison to the convenience of rapid customer service. This is similar to the practice of coffee shops that accept credit card payments without a signature for amounts below $25, because the risk of a credit-card chargeback is low while the cost of delaying the transaction to obtain a signature is comparatively larger. In contrast, selling a more expensive item for bitcoin runs the risk of a double-spend attack, where the buyer broadcasts a competing transaction that spends the same inputs (UTXO) and cancels the payment to the merchant. A double-spend attack can happen in two ways: either before a transaction is confirmed, or if the attacker takes advantage of a blockchain fork to undo several blocks. A 51% attack allows attackers to double-spend their own transactions in the new chain, thus undoing the corresponding transaction in the old chain. In our example, malicious attacker Mallory goes to Carol s gallery and purchases a beautiful triptych painting depicting Satoshi Nakamoto as Prometheus. Carol sells "The Great Fire" paintings for $250,000 in bitcoin, to Mallory. Instead of waiting for six or more confirmations on the transaction, Carol wraps and hands the paintings to Mallory after only one confirmation. Mallory works with an accomplice, Paul, who operates a large mining pool, and the accomplice launches a 51% attack as soon as Mallory s transaction is included in a block. Paul directs the mining pool to re-mine the same block height as the block containing Mallory s transaction, replacing Mallory s payment to Carol with a transaction that double-spends the same input as Mallory s payment. The double-spend transaction consumes the same UTXO and pays it back to Mallory s wallet, instead of paying it to Carol, essentially allowing Mallory to keep the bitcoin. Paul then directs the mining pool to mine an additional block, so as to make the chain containing the double-spend transaction longer than the original chain (causing a fork below the block containing Mallory s transaction). When the blockchain fork resolves in favor of the new (longer) chain, the double-spent transaction replaces the original payment to Carol. Carol is now missing the three paintings and also has no bitcoin payment. Throughout all this activity, Paul s mining pool participants might remain blissfully unaware of the double-spend attempt, because they mine with automated miners and cannot monitor every transaction or block. To protect against this kind of attack, a merchant selling large-value items must wait at least six confirmations before giving the product to the buyer. Alternatively, the merchant should use an escrow multi-signature account, again waiting for several confirmations after the escrow account is funded. The more confirmations elapse, the harder it becomes to invalidate a transaction with a 51% attack. For high-value items, payment by bitcoin will still be convenient and efficient even if the buyer has to wait 24 hours for delivery, which would ensure 144 confirmations. In addition to a double-spend attack, the other scenario for a consensus attack is to deny service to specific bitcoin participants (specific bitcoin addresses). An attacker with a majority of the mining power can simply ignore specific transactions. If they are included in a block mined by another miner, the attacker can deliberately fork and re-mine that block, again excluding the specific transactions. This type of attack can result in a sustained denial of service against a specific address or set of addresses for as long as the attacker controls the majority of the mining power. Despite its name, the 51% attack scenario doesn t actually require 51% of the hashing power. In fact, such an attack can be attempted with a smaller percentage of the hashing power. The 51% threshold is simply the level at which such an attack is almost guaranteed to succeed. A consensus attack is essentially a tug-of-war for the next block and the "stronger" group is more likely to win. With less 41

223 hashing power, the probability of success is reduced, because other miners control the generation of some blocks with their "honest" mining power. One way to look at it is that the more hashing power an attacker has, the longer the fork he can deliberately create, the more blocks in the recent past he can invalidate, or the more blocks in the future he can control. Security research groups have used statistical modeling to claim that various types of consensus attacks are possible with as little as 30% of the hashing power. The massive increase of total hashing power has arguably made bitcoin impervious to attacks by a single miner. There is no possible way for a solo miner to control more than a small percentage of the total mining power. However, the centralization of control caused by mining pools has introduced the risk of for-profit attacks by a mining pool operator. The pool operator in a managed pool controls the construction of candidate blocks and also controls which transactions are included. This gives the pool operator the power to exclude transactions or introduce double-spend transactions. If such abuse of power is done in a limited and subtle way, a pool operator could conceivably profit from a consensus attack without being noticed. Not all attackers will be motivated by profit, however. One potential attack scenario is where an attacker intends to disrupt the bitcoin network without the possibility of profiting from such disruption. A malicious attack aimed at crippling bitcoin would require enormous investment and covert planning, but could conceivably be launched by a well-funded, most likely state-sponsored, attacker. Alternatively, a well-funded attacker could attack bitcoin s consensus by simultaneously amassing mining hardware, compromising pool operators and attacking other pools with denial-ofservice. All of these scenarios are theoretically possible, but increasingly impractical as the bitcoin network s overall hashing power continues to grow exponentially. Undoubtedly, a serious consensus attack would erode confidence in bitcoin in the short term, possibly causing a significant price decline. However, the bitcoin network and software are constantly evolving, so consensus attacks would be met with immediate countermeasures by the bitcoin community, making bitcoin hardier, stealthier, and more robust than ever. 42

224 Alternative Chains, Valute, <phrase role="keep-together">e Applicazioni</phrase> Bitcoin è stato il risultato di 20 anni di ricerca in sistemi distribuiti e valute, e ha portato a una tecnologia rivoluzionaria nel suo campo: il meccanismo di consenso decentralizzato basato sulla proof of work. Questa invenzione al cuore di bitcoin ha generato un onda di innovazione in valute, servizi finanziari, economia, sistemi distribuiti, sistemi di votazione, corporate governance e contratti. In this chapter we ll examine the many offshoots of the bitcoin and blockchain inventions: the alternative chains, currencies, and applications built since the introduction of this technology in Mostly, we will look at alternative coins, or alt coins, which are digital currencies implemented using the same design pattern as bitcoin, but with a completely separate blockchain and network. For every alt coin mentioned in this chapter, 50 or more will go unmentioned, eliciting howls of anger from their creators and fans. The purpose of this chapter is not to evaluate or qualify alt coins, or even to mention the most significant ones based on some subjective assessment. Instead, we will highlight a few examples that show the breadth and variety of the ecosystem, noting the first-of-a-kind for each innovation or significant differentiation. Some of the most interesting examples of alt coins are in fact complete failures from a monetary perspective. That perhaps makes them even more interesting for study and highlights the fact that this chapter is not to be used as an investment guide. With new coins introduced every day, it would be impossible not to miss some important coin, perhaps the one that changes history. The rate of innovation is what makes this space so exciting and guarantees this chapter will be incomplete and out-of-date as soon as it is published. Una Tassonomia di Valute Alternative e Chains Bitcoin is an open source project, and its code has been used as the basis for many other software projects. The most common form of software spawned from bitcoin s source code are alternative decentralized currencies, or alt coins, which use the same basic building blocks to implement digital currencies. There are a number of protocol layers implemented on top of bitcoin s blockchain. These meta coins, meta chains, or blockchain apps use the blockchain as an application platform or extend the bitcoin protocol by adding protocol layers. Examples include Colored Coins, Mastercoin, NXT, and Counterparty. In the next section we will examine a few notable alt coins, such as Litecoin, Dogecoin, Freicoin, Primecoin, Peercoin, Darkcoin, and Zerocoin. These alt coins are notable for historical reasons or because they are good examples for a specific type of alt coin innovation, not because they are the most valuable or "best" alt coins. 1

225 In addition to the alt coins, there are also a number of alternative blockchain implementations that are not really "coins," which I call alt chains. These alt chains implement a consensus algorithm and distributed ledger as a platform for contracts, name registration, or other applications. Alt chains use the same basic building blocks and sometimes also use a currency or token as a payment mechanism, but their primary purpose is not currency. We will look at Namecoin and Ethereum as examples of alt chains. Finally, there are a number of bitcoin contenders that offer digital currency or digital payment networks, but without using a decentralized ledger or consensus mechanism based on proof of work, such as Ripple and others. These non blockchain technologies are outside the scope of this book and will not be covered in this chapter. Piattaforme di Meta Coin Meta coins and meta chains are software layers implemented on top of bitcoin, either implementing a currency-inside-a-currency, or a platform/protocol overlay inside the bitcoin system. These function layers extend the core bitcoin protocol and add features and capabilities by encoding additional data inside bitcoin transactions and bitcoin addresses. The first implementations of meta coins used various hacks to add metadata to the bitcoin blockchain, such as using bitcoin addresses to encode data or using unused transaction fields (e.g., the transaction sequence field) to encode metadata about the added protocol layer. Since the introduction of the OP_RETURN transaction scripting opcode, the meta coins have been able to record metadata more directly in the blockchain, and most are migrating to using that instead. Colored Coin Colored coins is a meta protocol that overlays information on small amounts of bitcoin. A "colored" coin is an amount of bitcoin repurposed to express another asset. Imagine, for example, taking a $1 note and putting a stamp on it that said, "This is a 1 share certificate of Acme Inc." Now the $1 serves two purposes: it is a currency note and also a share certificate. Because it is more valuable as a share, you would not want to use it to buy candy, so effectively it is no longer useful as currency. Colored coins work in the same way by converting a specific, very small amount of bitcoin into a traded certificate that represents another asset. The term "color" refers to the idea of giving special meaning through the addition of an attribute such as a color it is a metaphor, not an actual color association. There are no colors in colored coins. Colored coins are managed by specialized wallets that record and interpret the metadata attached to the colored bitcoins. Using such a wallet, the user will convert an amount of bitcoins from uncolored currency into colored coins by adding a label that has a special meaning. For example, a label could represent stock certificates, coupons, real property, commodities, or collectible tokens. It is entirely up to the users of colored coins to assign and interpret the meaning of the "color" associated with specific coins. To color the coins, the user defines the associated metadata, such as the type of issuance, whether it can be subdivided into smaller units, a symbol and description, and other related information. Once colored, these coins can be bought and sold, subdivided, and aggregated, and receive dividend payments. The colored coins can also be "uncolored" by removing the special 2

226 association and redeemed for their face value in bitcoin. To demonstrate the use of colored coins, we have created a set of 20 colored coins with symbol "MasterBTC" that represent coupons for a free copy of this book shown in Il profilo dei meta-dati di colored coin registrati come coupon per una copia gratuita del libro. Each unit of MasterBTC, represented by these colored coins, can now be sold or given to any bitcoin user with a colored-coincapable wallet, who can then transfer them to others or redeem them with the issuer for a free copy of the book. This example of colored coins can be seen here. Example 1. Il profilo dei meta-dati di colored coin registrati come coupon per una copia gratuita del libro { "source_addresses": [ "3NpZmvSPLmN2cVFw1pY7gxEAVPCVfnWfVD" ], "contract_url": " "name_short": "MasterBTC", "name": "Free copy of \"Mastering Bitcoin\"", "issuer": "Andreas M. Antonopoulos", "description": "This token is redeemable for a free copy of the book \"Mastering Bitcoin\"", "description_mime": "text/x-markdown; charset=utf-8", "type": "Other", "divisibility": 0, "link_to_website": false, "icon_url": null, "image_url": null, "version": "1.0" } Mastercoin Mastercoin is a protocol layer on top of bitcoin that supports a platform for various applications extending the bitcoin system. Mastercoin uses the currency MST as a token for conducting Mastercoin transactions but it is not primarily a currency. Rather, it is a platform for building other things, such as user currencies, smart property tokens, de-centralized asset exchanges, and contracts. Think of Mastercoin as an application-layer protocol on top of bitcoin s financial transaction transport layer, just like HTTP runs on top of TCP. Mastercoin operates primarily through transactions sent to and from a special bitcoin address called the "exodus" address (1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P), just like HTTP uses a specific TCP port (port 80) to differentiate its traffic from the rest of the TCP traffic. The Mastercoin protocol is gradually transitioning from using the specialized exodus address and multi-signatures to using the 3

227 OP_RETURN bitcoin operator to encode transaction metadata. Counterparty Counterparty is another protocol layer implemented on top of bitcoin. Counterparty enables user currencies, tradable tokens, financial instruments, decentralized asset exchanges, and other features. Counterparty is implemented primarily using the OP_RETURN operator in bitcoin s scripting language to record metadata that enhances bitcoin transactions with additional meaning. Counterparty uses the currency XCP as a token for conducting Counterparty transactions. Gli Alt Coin The vast majority of alt coins are derived from bitcoin s source code, also known as "forks." Some are implemented "from scratch" based on the blockchain model but without using any of bitcoin s source code. Alt coins and alt chains (in the next section) are both separate implementations of blockchain technology and both forms use their own blockchain. The difference in the terms is to indicate that alt coins are primarily used as currency, whereas alt chains are used for other purposes, not primarily currency. In senso stretto, il primo grande fork "alt" del codice di bitcoin non era un altcoin ma la alt chain Namecoin, di cui parleremo nella prossima sezione. Based on the date of announcement, the first alt coin that was a fork of bitcoin appeared in August 2011; it was called IXCoin. IXCoin modified a few of the bitcoin parameters, specifically accelerating the creation of currency by increasing the reward to 96 coins per block. In September 2011, Tenebrix was launched. Tenebrix was the first cryptocurrency to implement an alternative proof-of-work algorithm, namely scrypt, an algorithm originally designed for password stretching (brute-force resistance). The stated goal of Tenebrix was to make a coin that was resistant to mining with GPUs and ASICs, by using a memory-intensive algorithm. Tenebrix did not succeed as a currency, but it was the basis for Litecoin, which has enjoyed great success and has spawned hundreds of clones. Litecoin, in addition to using scrypt as the proof-of-work algorithm, also implemented a faster blockgeneration time, targeted at 2.5 minutes instead of bitcoin s 10 minutes. The resulting currency is touted as "silver to bitcoin s gold" and is intended as a light-weight alternative currency. Due to the faster confirmation time and the 84 million total currency limit, many adherents of Litecoin believe it is better suited for retail transactions than bitcoin. Alt coins continued to proliferate in 2011 and 2012, either based on bitcoin or on Litecoin.By 2013, there were 20 alt coins vying for position in the market. By the end of 2013, this number had exploded to 200, with 2013 quickly becoming the "year of the alt coins." The growth of alt coins continued in 2014, with more than 500 alt coins in existence at the time of writing. More than half the alt coins today are clones of Litecoin. Creating an alt coin is easy, which is why there are now more than 500 of them. Most of the alt coins 4

228 differ very slightly from bitcoin and do not offer anything worth studying. Many are in fact just attempts to enrich their creators. Among the copycats and pump-and-dump schemes, there are, however, some notable exceptions and very important innovations. These alt coins take radically different approaches or add significant innovation to bitcoin s design pattern. There are three primary areas where these alt coins differentiate from bitcoin: Poiitica monetaria differente Differenti meccanismi di consenso o proof of work Caratteristiche specifiche, come una forte anonimità Per ulteriori informazioni, consulta questo [linea temporale grafica di tutti gli alt coin e delle alt chain]. Valutare un Alt Coin With so many alt coins out there, how does one decide which ones are worthy of attention? Some alt coins attempt to achieve broad distribution and use as currencies. Others are laboratories for experimenting on different features and monetary models. Many are just get-rich-quick schemes by their creators. To evaluate alt coins, I look at their defining characteristics and their market metrics. Ecco un po di domande da farsi riguardo come un altcoin si differenzia da bitcoin: L alt coin introduce una innovazione significativa? C è una differenza sufficientemente coinvolgente per attrarre altri utenti fuori da bitcoin? L alt coin si rivolte a un interessante mercato di nicchia o specifica applicazione? Puo l alt coin attrarre abbastanza miner per essere protetto da attacchi riguardo al consenso delle transazioni? Ecco un po delle metriche finanziare e di mercato chiave da considerare: Qual è la capitalizzazione totale di mercato di un alt coin? Qual è la stima del numero di utenti/wallet che ha l alt coin? Quanti commercianti accettano l alt coin? Quante transazioni giornaliere (volume) sono eseguite sull alt coin? Quanto valore (fiat) è transato ogni giorno? In questo capitolo, ci concentreremo principalmente sulle caratteristiche tecniche e sul potenziale d innovazione degli alt coin rappresentati dal pimo gruppo di domande. Parametri Monetari Alternativi: Litecoin, Dogecoin, Freicoin Bitcoin has a few monetary parameters that give it distinctive characteristics of a deflationary fixedissuance currency. It is limited to 21 million major currency units (or 21 quadrillion minor units), it has 5

229 a geometrically declining issuance rate, and it has a 10-minute block "heartbeat," which controls the speed of transaction confirmation and currency generation. Many alt coins have tweaked the primary parameters to achieve different monetary policies. Among the hundreds of alt coins, some of the most notable examples include the following. Litecoin Uno dei primi altcoin, rilasciato nel Litecoin é la seconda valuta digitale con più successo dopo Bitcoin. Le sue innovazioni principali furono l uso di scrypt come algoritmo di proof-of-work (ereditato da Tenebrix) e i suoi parametri della moneta più veloci/leggeri. Tempo di generazione blocco: 2.5 minuti Moneta totale: 84 milioni di unità nel 2140 Algoritmo di consenso: proof of work Scrypt Capitalizzazione di mercato: $160 milioni a meta del 2014 Dogecoin Dogecoin was released in December 2013, based on a fork of Litecoin. Dogecoin is notable because it has a monetary policy of rapid issuance and a very high currency cap, to encourage spending and tipping. Dogecoin is also notable because it was started as a joke but became quite popular, with a large and active community, before declining rapidly in Tempo di generaizione blocco: 60 secondi Moneta totale: 100,000,000,000 (100 miliardi) di Doge nel 2015 Algoritmo di consenso: proof of work Scrypt Capitalizzazione di mercato: $12 milioni a metà del 2014 Freicoin Freicoin was introduced in July It is a demurrage currency, meaning it has a negative interest rate for stored value. Value stored in Freicoin is assessed a 4.5% APR fee, to encourage consumption and discourage hoarding of money. Freicoin is notable in that it implements a monetary policy that is the exact opposite of Bitcoin s deflationary policy. Freicoin has not seen success as a currency, but it is an interesting example of the variety of monetary policies that can be expressed by alt coins. Tempo di generazione blocco: 10 minuti Moneta totale: 100 millioni di unità nel 2140 Algoritmo di consenso: proof of work SHA256 Capitalizzazione di mercato: $130,000 a metà del

230 Innovazioni sul consenso: Peercoin, Myriad, Blackcoin, Vericoin, NXT Bitcoin s consensus mechanism is based on proof of work using the SHA256 algorithm. The first alt coins introduced scrypt as an alternative proof-of-work algorithm, as a way to make mining more CPUfriendly and less susceptible to centralization with ASICs. Since then, innovation in the consensus mechanism has continued at a frenetic pace. Several alt coins adopted a variety of algorithms such as scrypt, scrypt-n, Skein, Groestl, SHA3, X11, Blake, and others. Some alt coins combined multiple algorithms for proof of work. In 2013, we saw the invention of an alternative to proof of work, called proof of stake, which forms the basis of many modern alt coins. Proof of stake is a system by which existing owners of a currency can "stake" currency as interestbearing collateral. Somewhat like a certificate of deposit (CD), participants can reserve a portion of their currency holdings, while earning an investment return in the form of new currency (issued as interest payments) and transaction fees. Peercoin Peercoin è stato introdotto nell Agosto 2012 ed è il primo alt coin ad usare una proof ibrida, un algoritmo di proof-of-work e proof-of stake per emettere nuova valuta. Tempo di generazione blocco: 10 minuti Moneta totale: Nessun limite Algoritmo di consenso: (Ibrido) proof-of-stake con proof-of-work iniziale Capitalizzazione di mercato: $14 millioni a metà del 2014 Myriad Myriad was introduced in February 2014 and is notable because it uses five different proof-of-work algorithms (SHA256d, Scrypt, Qubit, Skein, or Myriad-Groestl) simultaneously, with difficulty varying for each algorithm depending on miner participation. The intent is to make Myriad immune to ASIC specialization and centralization as well as much more resistant to consensus attacks, because multiple mining algorithms would have to be attacked simultaneously. Generazione blocco: 30 secondi di media (target di 2.5 minuti per ogni algoritmo di mining) Moneta totale: 2 miliardi nel 2024 Algoritmo di consenso: Proof-of-work multi-algoritmo Capitalizzazione di mercato: $120,000 a metà del 2014 Blackcoin Blackcoin was introduced in February 2014 and uses a proof-of-stake consensus algorithm. It is also notable for introducing "multipools," a type of mining pool that can switch between different alt coins automatically, depending on profitability. Generazione blocco: 1 minuto 7

231 Moneta totale: Nessun limite Algoritmo di consenso: Proof-of-stake Capitalizzazione di mercato: $3.7 millioni a metà del 2014 VeriCoin VeriCoin was launched in May It uses a proof-of-stake consensus algorithm with a variable interest rate that dynamically adjusts based on market forces of supply and demand. It also is the first alt coin featuring auto-exchange to bitcoin for payment in bitcoin from the wallet. Generazione blocco: 1 minuto Moneta totale: Nessun limite Algoritmo di consenso: Proof-of-stake Capitalizzazione di mercato: $1.1 millioni a metà del 2014 NXT NXT (pronounced "Next") is a "pure" proof-of-stake alt coin, in that it does not use proof-of-work mining. NXT is a from-scratch implementation of a cryptocurrency, not a fork of bitcoin or any other alt coins. NXT implements many advanced features, including a name registry (similar to Namecoin), a decentralized asset exchange (similar to Colored Coins), integrated decentralized and secure messaging (similar to Bitmessage), and stake delegation (to delegate proof-of-stake to others). NXT adherents call it a "next-generation" or 2.0 cryptocurrency. Generazione blocco: 1 minuto Moneta totale: Nessun limite Algoritmo di consenso: Proof-of-stake Capitalizzazione di mercato: $30 millioni a metà del 2014 Innovazione Mining ad Obbiettivo-Doppio: Primecoin, Curecoin, Gridcoin Bitcoin s proof-of-work algorithm has just one purpose: securing the bitcoin network. Compared to traditional payment system security, the cost of mining is not very high. However, it has been criticized by many as being wasteful." The next generation of alt coins attempt to address this concern. Dualpurpose proof-of-work algorithms solve a specific "useful" problem, while producing proof of work to secure the network. The risk of adding an external use to the currency s security is that it also adds external influence to the supply/demand curve. Primecoin Primecoin was announced in July Its proof-of-work algorithm searches for prime numbers, computing Cunningham and bi-twin prime chains. Prime numbers are useful in a variety of scientific disciplines. The Primecoin blockchain contains the discovered prime numbers, thereby producing a 8

232 public record of scientific discovery in parallel to the public ledger of transactions. Generazione blocco: 1 minuto Moneta totale: Nessun limite Algoritmo di consenso: Proof of work con scoperta della catena dei numeri primi Capitalizzazione di mercato: $1.3 millioni a metà del 2014 Curecoin Curecoin was announced in May It combines a SHA256 proof-of-work algorithm with proteinfolding research through the Folding@Home project. Protein folding is a computationally intensive simulation of biochemical interactions of proteins, used to discover new drug targets for curing diseases. Tempo di generazione blocco: 10 minuti Moneta totale: Nessun limite Algoritmo di consenso: Proof of work con ricerca sul protein-folding Capitalizzazione di mercato: $58,000 a metà del 2014 Gridcoin Gridcoin was introduced in October It supplements scrypt-based proof of work with subsidies for participation in BOINC open grid computing. BOINC Berkeley Open Infrastructure for Network Computing is an open protocol for scientific research grid computing, which allows participants to share their spare computing cycles for a broad range of academic research computing. Gridcoin uses BOINC as a general-purpose computing platform, rather than to solve specific science problems such as prime numbers or protein folding. Generazione blocco: 150 secondi Moneta totale: Nessun limite Algoritmo di consenso: Proof-of-work con sussidio di BOINC grid-computing Capitalizzazione di mercato: $122,000 millioni a metà del 2014 Alt Coins Focalizzati sull Anonimità: CryptoNote, Bytecoin, Monero, Zerocash/Zerocoin, Darkcoin Bitcoin is often mistakenly characterized as "anonymous" currency. In fact, it is relatively easy to connect identities to bitcoin addresses and, using big-data analytics, connect addresses to each other to form a comprehensive picture of someone s bitcoin spending habits. Several alt coins aim to address this issue directly by focusing on strong anonymity. The first such attempt is most likely Zerocoin, a meta-coin protocol for preserving anonymity on top of bitcoin, introduced with a paper at the 2013 IEEE Symposium on Security and Privacy. Zerocoin will be implemented as a completely separate alt coin called Zerocash, in development at time of writing. An alternative approach to anonymity was 9

233 launched with CryptoNote in a paper published in October CryptoNote is a foundational technology that is implemented by a number of alt coin forks discussed next. In addition to Zerocash and CryptoNotes, there are several other independent anonymous coins, such as Darkcoin, that use stealth addresses or transaction re-mixing to deliver anonymity. Zerocoin/Zerocash Zerocoin è l approccio teoretico all anonimità della moneta digitale introdotta nel 2013 da ricercatori come Johns Hopkins. Zerocash è un implementazione alt-coin di Zerocoin che è in via di sviluppo e non ancora rilasciata. CryptoNote CryptoNote is a reference implementation alt coin that provides the basis for anonymous digital cash. It was introduced in October It is designed to be forked into different implementations and has a built-in periodic reset mechanism that makes it unusable as a currency itself. Several alt coins have been spawned from CryptoNote, including Bytecoin (BCN), Aeon (AEON), Boolberry (BBR), ducknote (DUCK), Fantomcoin (FCN), Monero (XMR), MonetaVerde (MCN), and Quazarcoin (QCN). CryptoNote is also notable for being a complete ground-up implementation of a crypto-currency, not a fork of bitcoin. Bytecoin Bytecoin was the first implementation spawned from CryptoNote, offering a viable anonymous currency based on the CryptoNote technology. Bytecoin was launched in July Note that there was a previous alt coin named Bytecoin with currency symbol BTE, whereas the CryptoNote-derived Bytecoin has the currency symbol BCN. Bytecoin uses the Cryptonight proof-of-work algorithm, which requires access to at least 2 MB of RAM per instance, making it unsuitable for GPU or ASIC mining. Bytecoin inherits ring signatures, unlinkable transactions, and blockchain analysis resistant anonymity from CryptoNote. Generazione blocco: 2 minuti Totale valuta: 184 miliardi di BCN Algoritmo di Consenso: Cryptonight proof of work Capitalizzazione di mercato: $3 millioni a metà del 2014 Monero Monero is another implementation of CryptoNote. It has a slightly flatter issuance curve than Bytecoin, issuing 80% of the currency in the first four years. It offers the same anonymity features inherited from CryptoNote. Generazione blocco: 1 minuto Valuta totale: 18.4 million XMR Algoritmo di Consenso: Cryptonight proof of work 10

234 Capitalizzazione di mercato: $5 millioni a metà del 2014 Darkcoin Darkcoin è stato lanciato nel Darkcoin implementa un sistema di moneta anonima usando un protocollo di re-mixing (rimescolamento) per tutte le transazioni chiamato DarkSend. Darkcoin è inoltre noto per l uso di 11 round di funzioni hash diverse (blake, bmw, groestl, jh, keccak, skein, luffa, cubehash, shavite, simd, echo) per l algoritmo di proof-of-work. Generazione blocco: 2.5 minuti Valuta totale: 22 milioni di DRK Algoritmo del Consenso: Multi-algoritmo a round multiplo proof of work Market capitalization: $19 million in mid-2014 Alt Chain Non-Monetarie Alt chains are alternative implementations of the blockchain design pattern, which are not primarily used as currency. Many include a currency, but the currency is used as a token for allocating something else, such as a resource or a contract. The currency, in other words, is not the main point of the platform; it is a secondary feature. Namecoin Namecoin was the first fork of the bitcoin code. Namecoin is a decentralized key-value registration and transfer platform using a blockchain. It supports a global domain-name registry similar to the domainname registration system on the Internet. Namecoin is currently used as an alternative domain name service (DNS) for the root-level domain.bit. Namecoin also can be used to register names and keyvalue pairs in other namespaces; for storing things like addresses, encryption keys, SSL certificates, file signatures, voting systems, stock certificates; and a myriad of other applications. The Namecoin system includes the Namecoin currency (symbol NMC), which is used to pay transaction fees for registration and transfer of names. At current prices, the fee to register a name is 0.01 NMC or approximately 1 US cent. As in bitcoin, the fees are collected by namecoin miners. I parametri base di Namecoin sono gli stessi di bitcoin: Tempo di generazione blocco: 10 minuti Valuta totale: 21 milioni di NMC nel 2140 Algoritmo di consenso: proof of work SHA256 Capitalizzazione di mercato: $10 milioni a metà del 2014 Namecoin s namespaces are not restricted, and anyone can use any namespace in any way. However, certain namespaces have an agreed-upon specification so that when it is read from the blockchain, application-level software knows how to read and proceed from there. If it is malformed, then 11

235 whatever software you used to read from the specific namespace will throw an error. Some of the popular namespaces are: d/ è il namespace dei nomi dominio per i domini.bit id/ is the namespace for storing person identifiers such as addresses, PGP keys, and so on u/ is an additional, more structured specification to store identities (based on openspecs) The Namecoin client is very similar to Bitcoin Core, because it is derived from the same source code. Upon installation, the client will download a full copy of the Namecoin blockchain and then will be ready to query and register names. There are three main commands: name_new Controlla o pre-registra un nome name_firstupdate Registra un nome e rendi la registrazione pubblica name_update Cambia i dettagli o esegui il refresh di una registrazione Per esempio, per registrare il dominio mastering-bitcoin.bit, usiamo il comando name_new come segue: $ namecoind name_new d/mastering-bitcoin [ ] "21cbab5b1241c6d1a6ad70a2416b3124eb883ac38e423e5ff591d1968eb6664a", "a05555e0fc56c023" The name_new command registers a claim on the name, by creating a hash of the name with a random key. The two strings returned by name_new are the hash and the random key (a05555e0fc56c023 in the preceding example) that can be used to make the name registration public. Once that claim has been recorded on the Namecoin blockchain it can be converted to a public registration with the name_firstupdate command, by supplying the random key: $ namecoind name_firstupdate d/mastering-bitcoin a05555e0fc56c023 "{"map": {"www": {"ip":" "}}}}" b7a2e59c0a26e5e ebeca c2f616ba579e6bc7f35ec234b01 This example will map the domain name to IP address The hash returned is the transaction ID that can be used to track this registration. You can see what names are 12

236 registered to you by running the name_list command: $ namecoind name_list [ ] { } "name" : "d/mastering-bitcoin", "value" : "{map: {www: {ip: }}}}", "address" : "NCccBXrRUahAGrisBA1BLPWQfSrups8Geh", "expires_in" : Namecoin registrations need to be updated every 36,000 blocks (approximately 200 to 250 days). The name_update command has no fee and therefore renewing domains in Namecoin is free. Third-party providers can handle registration, automatic renewal, and updating via a web interface, for a small fee. With a third-party provider you avoid the need to run a Namecoin client, but you lose the independent control of a decentralized name registry offered by Namecoin. Ethereum Ethereum is a Turing-complete contract processing and execution platform based on a blockchain ledger. It is not a clone of Bitcoin, but a completely independent design and implementation. Ethereum has a built-in currency, called ether, which is required in order to pay for contract execution. Ethereum s blockchain records contracts, which are expressed in a low-level, byte code like, Turingcomplete language. Essentially, a contract is a program that runs on every node in the Ethereum system. Ethereum contracts can store data, send and receive ether payments, store ether, and execute an infinite range (hence Turing-complete) of computable actions, acting as decentralized autonomous software agents. Ethereum can implement quite complex systems that are otherwise implemented as alt chains themselves. For example, the following is a Namecoin-like name registration contract written in Ethereum (or more accurately, written in a high-level language that can be compiled to Ethereum code): 13

237 if!contract.storage[msg.data[0]]: # La chiave è ancora disponibile? # Allora prendila! contract.storage[msg.data[0]] = msg.data[1] return(1) else: return(0) // Altrimenti non fare niente Il Futuro delle Valute The future of cryptographic currencies overall is even brighter than the future of bitcoin. Bitcoin introduced a completely new form of decentralized organization and consensus that has spawned hundreds of incredible innovations. These inventions will likely affect broad sectors of the economy, from distributed systems science to finance, economics, currencies, central banking, and corporate governance. Many human activities that previously required centralized institutions or organizations to function as authoritative or trusted points of control can now be decentralized. The invention of the blockchain and consensus system will significantly reduce the cost of organization and coordination on large-scale systems, while removing opportunities for concentration of power, corruption, and regulatory capture. 14

238 Sicurezza Bitcoin La sicurezza del bitcoin è complicata, perché il bitcoin non è un riferimento astratto ad un valore come può essere il saldo di un conto bancario. Bitcoin è molto più simile all idea del contante digitale, o all oro. Probabilmente avrete già sentito l espressione, "Possession is nine-tenths of the law" ("Il possedere è nove decimi della legge" - detto britannico riferito al sistema legislativo locale per cui chi possiede un bene è considerato legittimo proprietario fino a prova contraria). Beh, con bitcoin si può estremizzare questo concetto, e dire che chi possiede è il legittimo proprietario, punto. La proprietà delle chiavi per sbloccare il bitcoin è equivalente al possesso di denaro contante o di un pezzo di metallo prezioso. Il bitcoin può essere smarrito, perso, rubato, o è possibile accidentalmente versare un importo errato a qualcuno. In ognuno di questi casi, gli utenti non hanno diritto ad alcun ricorso, proprio come se fossero caduti loro dei contanti su un marciapiede pubblico. Tuttavia, bitcoin ha capacità che contanti, oro, e conti bancari non hanno. Un portafoglio bitcoin, contenente le chiavi, può essere sottoposto a backup come un qualsiasi file. Può essere conservato in copie multiple, o addirittura stampato su carta in copia fisica. Non è possibile effettuare un "backup" di contanti, oro, o conti bancari. Bitcoin è così diverso da tutto ciò è esistito fino ad ora che si presenta la necessità di concepire la sicurezza di questi in modo completamente nuovo. Principi sulla Sicurezza Il principio alla base di Bitcoin è il decentramento(decentralizzazione?), il quale ha importanti implicazioni per la sicurezza. Un modello centralizzato, come ad esempio una banca tradizionale o una rete di pagamento, dipende dal controllo degli accessi e dalla sorveglianza volta al tenere ogni possibile minaccia lontano dal sistema. Facendo un paragone, un sistema decentrato(decentralizzato?) come bitcoin sposta la responsabilità ed il controllo verso gli utenti. Poiché la sicurezza della rete è basata su prove di transazione piuttosto che sul controllo degli accessi, la rete può essere a modello aperto, e non è necessaria alcuna crittografia per il traffico dei bitcoin. In una rete di pagamento tradizionale, come ad esempio un sistema di carte di credito, il pagamento è 'open-end' perché contiene l identificativo privato dell utente (il numero di carta di credito). Dopo l addebito iniziale, chiunque abbia accesso all identificativo privato può "ritirare" denaro ed addebitare somme al proprietario più e più volte. Per questo motivo, la sicurezza della rete di pagamento deve essere garantita da un capo all altro con crittografia, e deve garantire che nessun intercettatore o intermediario possa compromettere il traffico dei pagamenti, sia nella fase di transito che nell archiviazione (in pausa). Se un malintenzionato riesce ad accedere al sistema, esso può compromettere transazioni in corso e payment token (gettoni di pagamento) che possono essere utilizzati per creare nuove transazioni. Peggio ancora, quando i dati dei clienti sono compromessi, i clienti sono esposti a rischio di furto di identità e devono intervenire per evitare l utilizzo fraudolento dei conti compromessi. Il sistema bitcoin è sensibilmente diverso. Una transazione bitcoin autorizza esclusivamente un valore specifico ad un destinatario specifico, e non può essere contraffatta o modificata. La transazione infatti non rivela alcuna informazione privata, come l identità delle parti, e non può essere utilizzata per 1

239 autorizzare pagamenti successivi. Pertanto, una rete di pagamento bitcoin non ha bisogno di essere criptata o protetta da intercettazioni. Anzi, è possibile persino trasmettere le transazioni bitcoin su un canale pubblico aperto, come reti Wi-Fi o Bluetooth, senza alcuna perdita/rischio? in termini di sicurezza. Il modello di sicurezza decentralizzato di bitcoin mette molto potere nelle mani degli utenti. Questo potere implica però la responsabilità di mantenere la segretezza delle proprie chiavi. Per la maggior parte degli utenti questo non è semplice, in particolare su dispositivi computerizzati generici come smartphone connessi ad Internet o computer portatili. Anche se il modello decentralizzato di impedisce il tipo di compromissione dati che avviene con sistemi di carte di credito, molti utenti non riescono a mantenere al sicuro le proprie chiavi in maniera adeguata e vengono derubati, uno per uno Sviluppare Sistemi Bitcoin Sicuri Il principio più importante per gli sviluppatori in ambito bitcoin è la decentralizzazione. La maggior parte degli sviluppatori avranno familiarità con i modelli di sicurezza centralizzati, e potrebbero essere tentati di applicare questi modelli ad applicazioni bitcoin, con risultati disastrosi. La sicurezza di bitcoin si basa sul controllo decentralizzato delle chiavi e sulla convalida indipendente delle transazioni da parte dei miner. Se si vuole mantenere la sicurezza bitcoin, è necessario assicurarsi di rimanere nel modello di sicurezza nato da bitcoin. In sostanza: non prendere possesso del controllo delle chiavi (private) di utenti, e non eseguire transazioni fuori dalla blockchain. Ad esempio, molti dei primi scambi in bitcoin concentravano tutti i fondi degli utenti in un unico portafoglio "caldo" con chiavi memorizzate su un unico server. Tale struttura rimuove il controllo da parte degli utenti e centralizza il controllo delle chiavi in un unico sistema. Molti di questi sistemi sono stati attaccati, con conseguenze disastrose per i loro clienti. Un altro errore comune è quello di portare le transazioni "off blockchain" (fuori dalla blockchain) tentando in modo errato di ridurre le spese di transazione o di accellerare l elaborazione delle transazioni. Un sistema "off blockchain" (fuori dalla blockchain) registrerà le operazioni su un libro mastro(database?) interno, centralizzato, sincronizzandole solo occasionalmente alla blockchain bitcoin. Questo sistema, ancora una volta, sostituisce al modello di sicurezza bitcoin decentralizzato un modello proprietario e centralizzato. Quando le operazioni sono "off blockchain" (fuori dalla blockchain), i libri mastro (database?) centralizzati protetti in maniera non adeguata possono essere falsificati, dirottando fondi ed esaurendo risparmi con operazioni che possono passare del tutto inosservate. A meno che non si sia disposti ad investire cospicuamente in sicurezza operativa, in livelli multipli di controllo degli accessi ed in verifiche (allo stesso modo delle banche tradizionali) si dovrebbe riflettere molto attentamente prima di portare dei fondi al di fuori del contesto di sicurezza decentralizzato bitcoin. Anche se si è in possesso dei fondi e delle competenze necessarie per realizzare un modello di sicurezza robusto, tale sistema non farebbe altro che replicare il fragile modello di reti finanziarie tradizionali afflitte da furto di identità, corruzione, e appropriazione indebita. Per usufruire del modello unico e decentralizzato di sicurezza bitcoin è necessario evitare la tentazione di produrre architetture centralizzate, il quale modello è sì familiare, ma sovverte la sicurezza di bitcoin nella sua 2

240 sostanza. La Radice della Fiducia L architettura di sicurezza tradizionale si basa su un concetto chiamato root of trust, un nucleo di fiducia utilizzato come base per la sicurezza dell intero sistema o applicazione. L architettura di sicurezza si sviluppa intorno alla root of trust come una serie di cerchi concentrici, simili agli strati di una cipolla, estendendo la fiducia dal centro verso l esterno. Ogni livello si basa sul livello interno più attendibile utilizzando controlli di accesso, firma digitale, crittografia ed altre informazioni primitive di sicurezza. Più i sistemi software diventano complessi, sono più propensi a contenere bug, che li rendono vulnerabili alla compromissione della sicurezza. Come risultato di ciò, più un sistema software diventa complesso, più è difficile proteggerlo. Il concetto di root of trust assicura che la maggior parte della fiducia sia posizionata all interno della parte meno complessa del sistema, e quindi meno vulnerabile, mentre l architettura del software più complessa è stratificata intorno ad esso. Questa architettura di sicurezza è ripetuta a scale diverse, in primo luogo stabilendo una root of trust all interno dell hardware di un unico sistema, quindi estendendo quella root of trust, attraverso il sistema operativo, a servizi di sistema di livello superiore, ed infine a molti server stratificati in cerchi concentrici in di fiducia che diminuisce andando verso l esterno. L architettura di sicurezza bitcoin è diversa. In bitcoin, il sistema di consenso crea un registro pubblico di fiducia completamente decentralizzato. Una blockchain la cui validità è verificata correttamente utilizza il genesis block (blocco genesi) come root of trust, costruendo una catena di fiducia che si estende fino al blocco attuale. I sistemi bitcoin possono, e devono, utilizzare la blockchain come root of trust. Se si progetta un applicazione bitcoin complessa, che consiste in servizi su diversi sistemi, è necessario esaminare attentamente l architettura di sicurezza, in modo da poter verificare dove viene posta la fiducia. In definitiva, l unica cosa a cui si può dare fiducia esplicitamente è una blockchain la cui validità è verificata completamente. Se nella vostra applicazione viene conferita fiducia, in modo esplicito o implicito, a qualsiasi componente che non sia la blockchain, la si dovrebbe considerare come una potenziale fonte di problemi, dato che introduce vulnerabilità. Un buon metodo per valutare l architettura di sicurezza della vostra applicazione è quello di considerare ogni singolo componente e valutare un ipotetico scenario in cui tale componente sia completamente compromesso e sotto il controllo di un malintenzionato. Considerare ogni componente della vostra applicazione e, uno alla volta, valutare l impatto sulla sicurezza complessiva se tale componente fosse compromesso. Se la vostra applicazione non è può più essere considerata sicura quando uno o più componenti sono compromessi, ciò mostra una collocazione errata della fiducia in tali componenti. Un applicazione bitcoin senza vulnerabilità dovrebbe essere vulnerabile solo come compromesso del meccanismo di consenso bitcoin, il che significa che la sua root of trust si basa sulla parte più forte della architettura di sicurezza bitcoin. I numerosi esempi di scambi bitcoin violati evidenziano l importanza di questo punto, perché la loro architettura di sicurezza ed il loro design fallisce anche le verifiche più superficiali. Queste implementazioni centralizzate avevano dato fiducia in modo esplicito a numerosi componenti di fuori della blockchain bitcoin, come gli hot wallet, registri database centralizzati, chiavi di crittografia vulnerabili, e altri schemi simili. 3

241 Le "Best Practices" sulla Sicurezza livello Utente Gli esseri umani hanno utilizzato controlli di sicurezza fisici per migliaia di anni. In confronto ciò, in quanto a sicurezza digitale abbiamo meno di 50 anni di esperienza. I sistemi operativi general purpose moderni non sono molto sicuri e non sono particolarmente adatti alla memorizzazione di denaro digitale. I nostri computer sono costantemente esposti a minacce esterne attraverso connessioni internet sempre in linea. Essi gestiscono migliaia di componenti software prodotti da centinaia di sviluppatori diversi, spesso con accesso senza vincoli ai file dell utente. Un unico componente software malevolo, tra le molte migliaia installati sul computer, può compromettere la tua tastiera e i tuoi file, rubando ogni bitcoin "contenuto" in applicazioni wallet. Il livello di manutenzione del computer necessario per mantenere un computer privo di virus e trojan è attuabile da una piccola minoranza di utenti, in quanto ben oltre il livello di competenza informatica di un utente medio. Nonostante decenni di ricerca e progresso nel campo della sicurezza delle informazioni, i beni digitali sono purtroppo ancora vulnerabili a nemici determinati. Persino i sistemi più altamente protetti ad accesso limitato, in società di servizi finanziari, agenzie di intelligence, e industria della difesa, sono spesso violati. Bitcoin crea risorse digitali che hanno un valore intrinseco e possono essere rubati e dirottati a nuovi proprietari immediatamente ed in maniera irrevocabil. Questo crea un incentivo enorme per gli hacker. Fino ad ora, gli hacker hanno dovuto convertire informazioni di identità o token di account ad esempio carte di credito, e conti bancari in beni dopo averli violati. Nonostante la difficoltà dei processi di schermaggio e di riciclaggio delle informazioni finanziarie, la quantità di furti che si verificati è sempre crescente. Bitcoin diminuisce questo problema perché non ha bisogno di essere schermato o riciclato; è un valore intrinseco di un bene digitale. Fortunatamente, bitcoin crea anche gli incentivi per migliorare la sicurezza informatica. Mentre in passato i rischi di compromissione del computer erano vaghi ed indiretti, bitcoin rende questi rischi chiari ed evidenti. Il possesso di bitcoin su computer serve a mettere a far meditare l utente sulla necessità di migliorare la sicurezza del computer. Come diretta conseguenza della proliferazione e dell aumento di utilizzatori di bitcoin e du altre valute digitali, si è potuta riscontrare un escalation sia di techniche di hacking che di soluzioni di sicurezza. In parole semplici, gli hacker hanno adesso un obiettivo molto allettante mentre gli utenti hanno un chiaro incentivo per difendersi. Nel corso degli ultimi tre anni, come risultato diretto dell aumento di utilizzatori di bitcoin, si è verificato un enorme progresso nel campo della sicurezza delle informazioni nelle forme di criptaggio hardware, salvataggio delle chiavi e wallet fisici (hardware wallet), nella tecnologia multi-signature, e in digital escrow. Nelle sezioni seguenti esamineremo diverse procedure consigliate per la sicurezza utente. Archiviazione Fisica dei Bitcoin Dato che la maggior parte degli utenti si trova molto più a suo agio con sicurezza fisica piuttosto che con sicurezza di informazioni, un metodo molto efficace per la protezione dei bitcoin è il convertirli in forma fisica. Le chiavi bitcoin non sono altro che lunghi numeri. Ciò significa che possono essere memorizzate in forma fisica, come ad esempio stampate su carta o incise su una moneta metallica. La sicurezza delle chiavi diventa a quel punto altrettanto semplice quanto il custodire la copia stampata 4

242 delle chiavi bitcoin. Un set di chiavi bitcoin che viene stampato su carta è chiamato "paper wallet", ed esistono molti strumenti gratuiti che possono essere utilizzati per crearli. Per quanto mi riguarda, custodisco la stragrande maggioranza dei miei bitcoin (99% o più) su dei paper wallet, cifrati con BIP0038, con più copie custodite in casseforti. Custodire bitcoin offline è definito come_cold storage_ ed è una delle tecniche di sicurezza più efficaci. Un sistema cold storage è un sistema in cui le chiavi vengono generate da un sistema offline (non si è mai connesso a Internet) e memorizzate offline su carta o su supporti digitali, come ad esempio una chiavetta USB. Wallet Hardware Con l avanzare del tempo, la sicurezza bitcoin adotterà in modo sempre crescente la forma di hardware wallet a prova di manomissione. A differenza di uno smartphone o di un computer desktop, un hardware wallet bitcoin ha un solo scopo: custodire i bitcoin in modo sicuro. Senza alcun software general-purpose a rischio di compromissioni e con interfacce limitate, gli hardware wallet sono in grado di offrire un livello quasi infallibile di sicurezza ad utenti non esperti. Prevedo che questi diventeranno il metodo più diffuso di custodire i bitcoin. Per un esempio di hardware wallet, si vedahttp:// Bilanciamento del Rischio Anche se la maggior parte degli utenti sono comprensibilmente preoccupati dai furti bitcoin, esiste un rischio ancor maggiore. I file di dati vengono smarriti continuamente. Se questi contengono bitcoin, la perdita può essere ancor più gravosa. Nel tentativo di proteggere i loro portafogli bitcoin, gli utenti devono stare molto attenti a non oltrepassare il limite, rischiando di perdere i propri bitcoin. Nel luglio del 2011, un progetto di sensibilizzazione ed educazione al bitcoin molto conosciuto perse quasi 7000 bitcoin. Cercando di impedire furti, i proprietari implementarono una serie complessa di backup crittografati. Alla fine di ciò, essi persero accidentalmente le chiavi di crittografia, rendendo i backup inutili e perdendo un intera fortuna. Così come nascondere i soldi seppellendoli nel deserto, se si proteggono i propri bitcoin 'troppo' bene si rischia di non essere in grado di ritrovarli. Diversificazione del Rischio Porteresti il tuo intero patrimonio netto in contanti nel tuo portafoglio? Quasi tutti considererebbero una cosa del genere piuttosto spericolata, tuttavia spesso gli utenti bitcoin tengono tutti i loro bitcoin in un unico wallet. Al contrario, gli utenti bitcoin dovrebbero frazionare il rischio suddividendo i propri possedimenti in diversi wallet bitcoin. Gli utenti prudenti manterranno solo una piccola frazione, forse meno del 5%, dei loro bitcoin in un wallet online o mobilewallet, come "spiccioli". Il resto dovrebbe essere diviso su diversi sistemi di deposito, come ad esempio un desktop wallet e offline (cold storage). Multi-sig e Amministrazione Ogni volta che una società o un individuo custodisce una grossa quantità di bitcoin, essi dovrebbero considerare la possibilià di utilizzare un indirizzo bitcoin multi-signature. Gli indirizzi multi-signature proteggono i fondi richiedendo più di una firma per effettuare il pagamento. Le chiavi di firma sono conservate in luoghi diversi e sotto il controllo di persone diverse. In un ambiente aziendale, per 5

243 esempio, le chiavi sono generate in modo indipendente e custodite da diversi dirigenti aziendali, per essere sicuri che nessuno possa compromettere i fondi aziendali da solo. Gli indirizzi multi-signature sono anche in grado di offrire ridondanza, con una persona singola che detiene diverse chiavi custodite in luoghi diversi. Sopravvivenza "bitcoin","morte del proprietario e")un importante considerazione riguardante la sicurezza che viene spesso trascurata è la disponibilità, specialmente nel contesto di incapacità o morte del proprietario delle chiavi. Spesso viene detto agli utenti bitcoin di utilizzare password complesse e di mantenere le loro chiavi al sicuro, non condividendole con nessun altro. Purtroppo, questa pratica rende quasi impossibile per la famiglia dell utente di recuperare i fondi se l utente non è più in grado di sbloccarli. Nella maggior parte dei casi, infatti, le famiglie degli utenti bitcoin potrebbero essere completamente all oscuro dell esistenza di tali fondi bitcoin. Se possiedi molti bitcoin, dovresti considerare condividere i dettagli di accesso con un parente fidato o un avvocato. Uno schema di sopravvivenza più complesso potrebbe essere quello di impostare un accesso multi-signature e una pianifica dei beni attraverso un un avvocato specializzato come "digital asset executor." Conclusioni Bitcoin è una tecnologia completamente nuova, senza precedenti e relativamente complessa. Man mano che passa il tempo svilupperemo strumenti migliori per la sicurezza e metodologie più semplici da applicare per i non esperti. Per ora, gli utenti di bitcoin possono utilizzare molti dei suggerimenti discussi in questo libro per godere di un esperienza sicura e senza problemi. 6

244 Appendix A: Comandi Bitcoin Explorer (bx) Utilizzo: bx COMMAND [--help] Info: I comandi bx sono: address-decode address-embed address-encode address-validate base16-decode base16-encode base58-decode base58-encode base58check-decode base58check-encode base64-decode base64-encode bitcoin160 bitcoin256 btc-to-satoshi ec-add ec-add-secrets ec-multiply ec-multiply-secrets ec-new ec-to-address ec-to-public ec-to-wif fetch-balance fetch-header fetch-height fetch-history fetch-stealth fetch-tx fetch-tx-index hd-new hd-private hd-public hd-to-address hd-to-ec hd-to-public hd-to-wif help input-set 1

245 input-sign input-validate message-sign message-validate mnemonic-decode mnemonic-encode ripemd160 satoshi-to-btc script-decode script-encode script-to-address seed send-tx send-tx-node send-tx-p2p settings sha160 sha256 sha512 stealth-decode stealth-encode stealth-public stealth-secret stealth-shared tx-decode tx-encode uri-decode uri-encode validate-tx watch-address wif-to-ec wif-to-public wrap-decode wrap-encode Per maggiori informazioni, vedi la home page di Bitcoin Explorer e la documentazione per l utente di Bitcoin Explorer. Esempi d uso del comando bx Guardiamo a un po di esempi d uso di Bitcoin Explorer per sperimentare con chiavi e indirizzi: Genera un valore "seed" random usando il comando seed, che usa il generatore di numeri casuali del sistema operativo. Passa il seed al comando ec-new per generare una nuova chiave privata. Salviamo l output (stdout) nel file private_key: 2

246 $ bx seed bx ec-new > private_key $ cat private_key 73096ed11ab9f1db ece7d73ea7c bcc4bbc de474 Ora, genera la chiave pubblica dalla chiave privata usando il comando ec-to-public. Passiamo il file private_key nello standard input e salviamo lo standard output del comando in un nuovo file public_key: $ bx ec-to-public < private_key > public_key $ cat public_key 02fca46a6006a62dfdd2dbb d0d97a04f430f12a7626dd409256c12be500 Possiamo cambiare formato alla public_key e farla diventare un indirizzo usando il comando ec-toaddress. Passiamo la public_key come standard input: $ bx ec-to-address < public_key 17re1S4Q8ZHyCP8Kw7xQad1Lr6XUzWUnkG Le chiavi generate in questa maniera producono un wallet type-0 non-deterministico. Questo significa che ogni chiave è generata da un seed bitcoin indipendente. I comandi Bitcoin Explorer possono anche generare chiave deterministicamente, in conformità con il BIP0032. In questo caso, una chiave "master" è creata da un seed e successivamente estesa deterministicamente per produrre un albero di sotto-chiavi, risultante in un wallet deterministico type-2. Per cominciare usiamo i comandi seed e hd-new per generare una to generate a una chiave master che verrà usata come base per derivare una gerarchia di chiavi. $ bx seed > seed $ cat seed eb68ee9f3df6bd4441a9feadec179ff1 $ bx hd-new < seed > master $ cat master xprv9s21zrqh143k2behmypnqouvagiejaravazactgsage6lsanwubeitcdzd23maoyizm9cape51gnflmkbqkyo WWMCRwzfuJk8RwF1SVEpAQ A questo punto usiamo il comando hd-private per generare una chiave dell'"account" "hardened" e una sequenza di due chiavi private all interno dell account. 3

247 $ bx hd-private --hard < master > account $ cat account xprv9vkdlt81dtkjwhb8fsvb5qk8cgnzvechzsrtcfvu3amwvqathp59ueufuyq8qi3qpjk4aksbmbfxwcgs8pybg or2nwhelyvg4dhoee68a1n $ bx hd-private --index 0 < account xprv9xhfb6w1vx9xgzypnxvgahpxssekercpheuv5ijcvesuueacvr3nry3fpghcnbidbvg4lgndirdsia1e9f3dw PkX7Tp1V1u97HKG1FJwUpU $ bx hd-private --index 1 < account xprv9xhfb6w1vx9xjc8xbn4gn86jznaz6xheqyxzblb4fzhfd6vqclpgrzfsdjsumveradbgdbzicrjru9n6tzewr ASVpEdrZrFidt1RDfn4yA3 Successivamente usiamo il comando hd-public per generare la sequenza corrispondente di due chiavi pubbliche. $ bx hd-public --index 0 < account xpub6bh1zctuktifu43ruz2gxqlgzu5f3tleetq5t6ie3aqtm2vmtxmcyln9fyhighgpqe9qqymql2eypfj3vezhz 5wzaSW4FiGrseNDR4LKqTy $ bx hd-public --index 1 < account xpub6bh1zctuktifx6czhpbgjg3uyq13wr16cmtbpiagekpevtpyjshwymamv1cn7nupukgqhpvxjvqsra8xwbgqd hohecdfteymvyzwrd7juf8 Le chiavi pubbliche possono essere derivate anche dalle chiave privati corrispondenti usando il comando hd-to-public. $ bx hd-private --index 0 < account bx hd-to-public xpub6bh1zctuktifu43ruz2gxqlgzu5f3tleetq5t6ie3aqtm2vmtxmcyln9fyhighgpqe9qqymql2eypfj3vezhz 5wzaSW4FiGrseNDR4LKqTy $ bx hd-private --index 1 < account bx hd-to-public xpub6bh1zctuktifx6czhpbgjg3uyq13wr16cmtbpiagekpevtpyjshwymamv1cn7nupukgqhpvxjvqsra8xwbgqd hohecdfteymvyzwrd7juf8 Possiamo generare un numero di chiavi praticamente senza limiti in una catena deterministica, tutte derivate da un singolo seed. Questa tecnica è usata in molte applicazioni wallet per generare chiavi che possono essere archiviate (backup) e ripristinate con un singolo valore seed. E' molto piu facile che dover effettuare il backup del wallet con tutte le chiavi generate randomicamente ogni volta che si crea una nuova chiave. Il seed può essere codificato usando il comando mnemonic-encode. 4

248 $ bx hd-mnemonic < seed > words adore repeat vision worst especially veil inch woman cast recall dwell appreciate A questo punto il seed può essere decodificato usanto il comando mnemonic-decode. $ bx mnemonic-decode < words eb68ee9f3df6bd4441a9feadec179ff1 La codifica mnemonica può rendere il seed più facile da appuntare e anche da memorizzare. 5

249 Appendix A: Bitcoin Improvement Proposals (Proposte per il Miglioramento di Bitcoin) I Bitcoin improvement proposals (Proposte per il miglioramento di Bitcoin) sono documenti di design che forniscono informazioni sulla comunità bitcoin, o descrivono una nuova funzionalità per bitcoin, o per i suoi processi o per l ecosistema. Seguendo gli Scopi e linee guida dei BIP contenute nel BIP0001, ci sono tre tipi di BIP: Standard BIP Descrive ogni cambiamento che interessa la maggior parte o tutte le implementazioni bitcoin, come un cambio nel protocollo di rete, un cambio nelle regole di validità delle transazioni, o ogni tipo di cambiamento o aggiunta che interessa l interoperabilità delle applicazioni che usano bitcoin. Informational BIP (BIP informativo) Descrive un problema di design di bitcoin, o fornisce linee guida generali o informazioni alla comunità bitcoin, ma non propone una nuova funzionalità. Gli Informational BIP non rappresentano necessariamente un consenso della comunità bitcoin o un consiglio, in questo modo gli utenti e gli implementatori possono ignorare i BIP informativi o seguire il loro consiglio. Process BIP (BIP di processo) Descrive un processo bitcoin, o propone un cambiamento a (o un evento in) un processo. I Process BIP sono come i BIP standard ma si applicano su aree diverse dal protocollo bitcoin stesso. Questi possono proporre un implementazione, ma non al codice bitcoin; essi richiedono generalmente un consenso della community; e diversamente dagli informational BIP, sono più di semplici consigli, e gli utenti sono tipicamente consigliati a non ignorarli. Esempi includono procedure, linee guida, cambiamenti al processo di presa delle decisioni, e cambiamenti agli strumenti o alle situazioni usate nello sviluppo di Bitcoin. Ogni meta-bip è inoltre considerato un BIP di processo. Le Bitcoin improvement proposals sono registrate in un repository versionato su GitHub. Stato dei BIPs mostra una "fotografia" dei BIP nell autunno Consulta il repository autoritativo per informazioni aggiornate sui BIP esistenti e i loro contenuti. Table 1. Stato dei BIPs BIP# Link Titolo Proprietario Tipo Status 1 om/bitcoin/bip s/blob/master/b ip mediawik i BIP Motivi e Linee Guida Amir Taaki Standard Attiva 1

250 BIP# Link Titolo Proprietario Tipo Status 10 om/bitcoin/bip s/blob/master/b ip mediawik i Distribuzione delle Transazioni Multi-Sig Alan Reiner Informativa Bozza 11 om/bitcoin/bip s/blob/master/b ip mediawik i M-di-N Transazioni Standard Gavin Andresen Standard Accettata 12 om/bitcoin/bip s/blob/master/b ip mediawik i OP_EVAL Gavin Andresen Standard Revocata 13 om/bitcoin/bip s/blob/master/b ip mediawik i Formato dell indirizzo per l hash Gavin Andresen Standard Finale 14 om/bitcoin/bip s/blob/master/b ip mediawik i Versione del Protocollo e User Agent Amir Taaki, Patrick Strateman Standard Accettata 15 om/bitcoin/bip s/blob/master/b ip mediawik i Alias Amir Taaki Standard Ritirato 16 om/bitcoin/bip s/blob/master/b ip mediawik i Pay To Script Hash Gavin Andresen Standard Accettato 2

251 BIP# Link Titolo Proprietario Tipo Status 17 om/bitcoin/bip s/blob/master/b ip mediawik i OP_CHECKHAS HVERIFY (CHV) Luke Dashjr Ritirata Bozza 18 om/bitcoin/bip s/blob/master/b ip mediawik ilink: 19 om/bitcoin/bip s/blob/master/b ip mediawik i hashscriptchec k Transazioni Standard M-di- N (Low SigOp) Luke Dashjr Standard Bozza Luke Dashjr Standard Bozza 20 om/bitcoin/bip s/blob/master/b ip mediawik i Schema URI Luke Dashjr Standard Sostituito 21 om/bitcoin/bip s/blob/master/b ip mediawik i Schema URI Nils Schneider, Matt Corallo Standard Accettato 22 om/bitcoin/bip s/blob/master/b ip mediawik i 23 om/bitcoin/bip s/blob/master/b ip mediawik i getblocktempla te - Fondamentali getblocktempla te - Mining attraverso Pool Luke Dashjr Standard Accettata Luke Dashjr Standard Accettata 3

252 BIP# Link Titolo Proprietario Tipo Status 30 om/bitcoin/bip s/blob/master/b ip mediawik i 31 om/bitcoin/bip s/blob/master/b ip mediawik i 32 om/bitcoin/bip s/blob/master/b ip mediawik i Transazioni Duplicate Messaggio Pong Wallet Gerarchici Deterministici Pieter Wuille Standard Accettato Mike Hearn Standard Accettata Pieter Wuille Informational Accettata 33 om/bitcoin/bip s/blob/master/b ip mediawik i Nodi Stratizzati Amir Taaki Standard Bozza 34 om/bitcoin/bip s/blob/master/b ip mediawik i Block v2, Altezza nella coinbase Gavin Andresen Standard Accettata 35 om/bitcoin/bip s/blob/master/b ip mediawik i messaggio mempool Jeff Garzik Standard Accettata 36 om/bitcoin/bip s/blob/master/b ip mediawik i Servizi Custom Stefan Thomas Standard Bozza 4

253 BIP# Link Titolo Proprietario Tipo Status 37 om/bitcoin/bip s/blob/master/b ip mediawik i Filtraggio Bloom Mike Hearn and Matt Corallo Standard Accettata 38 om/bitcoin/bip s/blob/master/b ip mediawik i 39 om/bitcoin/bip s/blob/master/b ip mediawik i Chiave privata protetta-dapassword Codice mnemonico per generare wallet deterministici keys 40 Protocollo di rete Stratum 41 Protocollo di mining Stratum 42 om/bitcoin/bip s/blob/master/b ip mediawik i 43 om/bitcoin/bip s/blob/master/b ip mediawik i 44 om/bitcoin/bip s/blob/master/b ip mediawik i Una fornitura monetaria finita per bitcoin Campo Purpose per Wallet Deterministici Gerarchia Multi-Account Hierarchy per Wallet Deterministici Wallets Mike Caldwell Standard Bozza Slush Standard Bozza Slush Standard Numero allocato BIP Slush Standard Numero allocato BIP Pieter Wuille Standard Bozza Slush Standard Bozza Slush Standard Bozza 5

254 BIP# Link Titolo Proprietario Tipo Status 50 om/bitcoin/bip s/blob/master/b ip mediawik i Post-Mortem del Fork A Catena del Marzo 2013 Gavin Andresen Informativa Bozza 60 om/bitcoin/bip s/blob/master/b ip mediawik i Messaggio di "versione" a Lunghezza Fissa (Relay- Transactions Field) Amir Taaki Standard Bozza 61 om/bitcoin/bip s/blob/master/b ip mediawik i "rifiuta" messaggio P2P Gavin Andresen Standard Bozza 62 om/bitcoin/bip s/blob/master/b ip mediawik i Gestire la malleability Pieter Wuille Standard Bozza 63 Stealth Address Peter Todd Standard numero BIP allocato 64 om/bitcoin/bip s/blob/master/b ip mediawik i messaggio getutxos Mike Hearn Standard Bozza 70 om/bitcoin/bip s/blob/master/b ip mediawik i Protocollo di pagamento Gavin Andresen Standard Bozza 6

255 BIP# Link Titolo Proprietario Tipo Status 71 om/bitcoin/bip s/blob/master/b ip mediawik i MIME types del Protocollo di Pagamento Gavin Andresen Standard Bozza 72 om/bitcoin/bip s/blob/master/b ip mediawik i URIs per il protocollo di pagamento Gavin Andresen Standard Bozza 73 om/bitcoin/bip s/blob/master/b ip mediawik i Utilizza l header "Accept" con le Payment Request URLs Stephen Pair Standard Bozza 7

256 Appendix A: pycoin, ku, e tx La libreria Python pycoin, scritta originariamente e mantenuta da Richard Kiss, è una libreria Python che supporta la manipolazione di chiavi e transazioni bitcoin, e supporta anche il linguaggio di scripting abbastanza da gestire adeguatamente transazioni non-standard. La libreria pycoin supporta sia Python 2 (2.7.x) e Python 3 (successivo alla 3.3); e viene fornito con utilità da riga di comando molto utili, ku e tx. Key Utility (KU) La utility da riga di comando ku ("key utility") è uno strumento multifunzione per manipolare le chiavi. Supporta le chiavi BIP32, il WIF, e gli indirizzi (bitcoin e altcoin). Di seguito potrai trovare qualche esempio. Crea una chiave BIP32 usando fonti di entropia di base fornita da GPG e da /dev/random: 1

257 $ ku create input : create network : Bitcoin wallet key : xprv9s21zrqh143k3lu5ctpztbnb9ktja5su9dcwhvxjemijbsy7vqxug7hipgdwau m2nhnzdvxjf5kjo9vjp2nabx65c5sfswsv8oxcbpehtji public version : xpub661mymwaqrbcfpyyiuvzpkjkhnjdzyakwsy76jvvd7fh4fsg3nqiov2cfxzxy8 DGcpfT56AMFeo8M8KPkFMfLUtvwjwb6WPv8rY65L2q8Hz tree depth : 0 fingerprint : 9d9c6092 parent f'print : child index : 0 chain code : 80574fb260edaa4905bc86c9a47d30c697c50047ed466c0d4a5167f6821e8f3c private key : yes secret exponent : hex : f8a8a28b28a916e1043cc0aca52033a18a13cab1638d bc171fddfbe wif : L5Z54xi6qJusQT42JHA44mfPVZGjyb4XBRWfxAzUWwRiGx1kV4sP uncompressed : 5KhoEavGNNH4GHKoy2Ptu4KfdNp4r56L5B5un8FP6RZnbsz5Nmb public pair x : public pair y : x come hex : a90b fa e09a8e4adf928bdbdb9dad e y come hex : 843a0f6ed9c0eb1962c fe3f1957c f4fe245a4fcd625 y parity : dispari key pair as sec : 03a90b fa e09a8e4adf928bdbdb9dad e uncompressed : 04a90b fa e09a8e4adf928bdbdb9dad e a0f6ed9c0eb1962c fe3f1957c f4fe245a4fcd625 hash160 : 9d9c ae323acfc96c852753fe3c8819d uncompressed : 8870d869800c9b91ce1eb460f4c60540f87c15d7 Indirizzo Bitcoin : 1FNNRQ5fSv1wBi5gyfVBs2rkNheMGt86sp uncompressed : 1DSS5isnH4FsVaLVjeVXewVSpfqktdiQAM Crea una chiave BIP32 da una passphrase: La passphrase in questo esempio è troppo semplice da indovinare. 2

258 $ ku P:foo input : P:foo network : Bitcoin wallet key : xprv9s21zrqh143k31agnk5pyvvw23ghnkbq2wh5aek6g1s496m8zmjxncckzkgb5j ZoY5eSJMJ2Vbyvi2hbmQnCuHBujZ2WXGTux1X2k9Krdtq public version : xpub661mymwaqrbcfvf9ulcqldsea5wnccugqacgnd9iemq31tgh6u4dlqwoqayvts VYFvXz2vPPpbXE1qpjoUFidhjFj82pVShWu9curWmb2zy tree depth : 0 fingerprint : 5d353a2e parent f'print : child index : 0 chain code : 5eeb1023fd6dd1ae52a005ce0e e1d90e08be980a85e9111fd7646bbc private key : yes esponente segreto (secret exponent) : hex : 91880b0e3017ba586b735fe7d04f1790f3c46b818a2151fb2def5f14dd2fd9c3 wif : L26c3H6jEPVSqAr1usXUp9qtQJw6NHgApq6Ls4ncyqtsvcq2MwKH uncompressed : 5JvNzA5vXDoKYJdw8SwwLHxUxaWvn9mDea6k1vRPCX7KLUVWa7W public pair x : public pair y : x in hex : b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f y in hex : 826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c de52 parità y : pari key pair come sec : 02b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f non-compressa : 04b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f 826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c de52 hash160 : 5d353a2ecdb d57a3f11de0c19286 uncompressed : e5bd3a7e6cb62b4c820e51200fb1c148d79e67da Indirizzo Bitcoin : 19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii uncompressed : 1MwkRkogzBRMehBntgcq2aJhXCXStJTXHT Ottieni info come JSON: $ ku P:foo -P -j 3

259 { "y_parity": "even", "public_pair_y_hex": "826d8b4d3010aea16ff4c1c1d3ae68541d9a04df54a2c48cc241c de52", "private_key": "no", "parent_fingerprint": " ", "tree_depth": "0", "network": "Bitcoin", "btc_address_uncompressed": "1MwkRkogzBRMehBntgcq2aJhXCXStJTXHT", "key_pair_as_sec_uncompressed": "04b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f826d8b4d3010aea16ff4c1 c1d3ae68541d9a04df54a2c48cc241c de52", "public_pair_x_hex": "b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f", "wallet_key": "xpub661mymwaqrbcfvf9ulcqldsea5wnccugqacgnd9iemq31tgh6u4dlqwoqayvtsvyfvxz2vpppbxe1qpjoufi dhjfj82pvshwu9curwmb2zy", "chain_code": "5eeb1023fd6dd1ae52a005ce0e e1d90e08be980a85e9111fd7646bbc", "child_index": "0", "hash160_uncompressed": "e5bd3a7e6cb62b4c820e51200fb1c148d79e67da", "btc_address": "19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii", "fingerprint": "5d353a2e", "hash160": "5d353a2ecdb d57a3f11de0c19286", "input": "P:foo", "public_pair_x": " ", "public_pair_y": " ", "key_pair_as_sec": "02b4e599dfa44555a4ed38bcfff0071d5af676a86abf123c5b4b4e8e67a0b0b13f" } Chiave pubblica BIP32: $ ku -w -P P:foo xpub661mymwaqrbcfvf9ulcqldsea5wnccugqacgnd9iemq31tgh6u4dlqwoqayvtsvyfvxz2vpppbxe1qpjoufid hjfj82pvshwu9curwmb2zy Genera una sottochiave: 4

260 $ ku -w -s3/2 P:foo xprv9wtertskjvyja1v4cutfmfkwme5eu8erbqcs9xajnsuzcbt7ykhawdrxvg3g3f6bfk7ms5hhbvmbdutnmyg6i ogwkxx6mefew4m8erolgkj Sottochiave Hardened: $ ku -w -s3/2h P:foo xprv9wtertsu5awgkdeupmqbcbzwx1xq85znx9iqrqw9dxwygfp7irgjo79dsvctcschsnz3xu3dhsuagzbdh8idk BN45k67UKsJUXM1JfRCdn1 WIF: $ ku -W P:foo L26c3H6jEPVSqAr1usXUp9qtQJw6NHgApq6Ls4ncyqtsvcq2MwKH Indirizzo: $ ku -a P:foo 19Vqc8uLTfUonmxUEZac7fz1M5c5ZZbAii Genera una serie di sottochiavi: $ ku P:foo -s 0/0-5 -w xprv9xwkbdfybxmzjbg9eixbpy67kk72fphup9utjokebftjsjiukuudf5v3tu8u8cdzytqynsekc8byujs8g3bhx xkwb89ggn2dzlcojsuedrk xprv9xwkbdfybxmznzkf3bagifk593gt7wjzpnyamvc77guqvej5qhckc5adtwxa28acmani9xhcrrvtfqqcuxt8r UgFz3souMiDdWxJDZnQxzx xprv9xwkbdfybxmzqdxa8y4swqfbdy71gsw9sjx9jpcijeibwsmqyrxan6srxupbtj3ptxqfkzjaiwoupmvtrxkzu 4zfsnr3pqyy2vthpkwuoVq xprv9xwkbdfybxmzsa85gywj9uypyoqv826yaadkwmaaeosnrfbkgj2tqwuiwy3zuqxygphfv9cngj5p7e8eskpzk L1Y8Gk9aX6QbryA5raK73p xprv9xwkbdfybxmzv2q3n66hhz8dacenqdnxml1j62krjacf7xb1hjwuw2vmjqrcofy2jtfxdiey8usrnjfqk6dad yzxomvtalhywqx3fs4a9zw xprv9xwkbdfybxmzw4jeyxuhyc9ft25k9irp87n2rqfj5bqbjkdt84mm7wtc2xmzfukg7iyf7xfhkkssaykwkjbr5 4bnyAD9GzjUYbAYTtN4ruo 5

261 Genera gli indirizzi corrispondenti: $ ku P:foo -s 0/0-5 -a 1MrjE78H1R1rqdFrmkjdHnPUdLCJALbv3x 1AnYyVEcuqeoVzH96zj1eYKwoWfwte2pxu 1GXr1kZfxE1FcK6ZRD5sqqqs5YfvuzA1Lb 116AXZc4bDVQrqmcinzu4aaPdrYqvuiBEK 1Cz2rTLjRM6pMnxPNrRKp9ZSvRtj5dDUML 1WstdwPnU6HEUPme1DQayN9nm6j7nDVEM Generate the corresponding WIFs: $ ku P:foo -s 0/0-5 -W L5a4iE5k9gcJKGqX3FWmxzBYQc29PvZ6pgBaePLVqT5YByEnBomx Kyjgne6GZwPGB6G6kJEhoPbmyjMP7D5d3zRbHVjwcq4iQXD9QqKQ L4B3ygQxK6zH2NQGxLDee2H9v4Lvwg14cLJW7QwWPzCtKHdWMaQz L2L2PZdorybUqkPjrmhem4Ax5EJvP7ijmxbNoQKnmTDMrqemY8UF L2oD6vA4TUyqPF8QG4vhUFSgwCyuuvFZ3v8SKHYFDwkbM765Nrfd KzChTbc3kZFxUSJ3Kt54cxsogeFAD9CCM4zGB22si8nfKcThQn8C Controlla che funzioni scegliendo una stringa BIP32 (quella corrispondente alla sottochiave 0/3): $ ku -W xprv9xwkbdfybxmzsa85gywj9uypyoqv826yaadkwmaaeosnrfbkgj2tqwuiwy3zuqxygphfv9cngj5p7e8eskpzk L1Y8Gk9aX6QbryA5raK73p L2L2PZdorybUqkPjrmhem4Ax5EJvP7ijmxbNoQKnmTDMrqemY8UF $ ku -a xprv9xwkbdfybxmzsa85gywj9uypyoqv826yaadkwmaaeosnrfbkgj2tqwuiwy3zuqxygphfv9cngj5p7e8eskpzk L1Y8Gk9aX6QbryA5raK73p 116AXZc4bDVQrqmcinzu4aaPdrYqvuiBEK Sì, sembra familiare. Dall esponente segreto: 6

262 $ ku 1 input : 1 network : Bitcoin esponente segreto : 1 esadecimale : 1 wif : KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn non-compressa : 5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf coppia pubblica x : coppia pubblica y : x in esadecimale : 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 y in esadecimale : 483ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 parità y : pari key pair come sec : 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 non-compressa : 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 hash160 : 751e76e d454941c45d1b3a323f1433bd6 non-compresso : 91b24bf9f ac687abb035127b1d28a5 Indirizzo Bitcoin : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH non-compressa : 1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm Versione Litecoin: 7

263 $ ku -nl 1 input : 1 network : Litecoin esponente segreto: 1 hex : 1 wif : T33ydQRKp4FCW5LCLLUB7deioUMoveiwekdwUwyfRDeGZm76aUjV non-compressa: 6u823ozcyt2rjPH8Z2ErsSXJB5PPQwK7VVTwwN4mxLBFrao69XQ coppia pubblica x: coppia pubblica y : x in esadecimale : 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 y in esadecimale : 483ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 parità y : pari key pair come sec : 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 non-compresso : 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 hash160 : 751e76e d454941c45d1b3a323f1433bd6 non-compressa : 91b24bf9f ac687abb035127b1d28a5 Indirizzo Litecoin : LVuDpNCSSj6pQ7t9Pv6d6sUkLKoqDEVUnJ uncompressed : LYWKqJhtPeGyBAw7WC8R3F7ovxtzAiubdM Dogecoin WIF: $ ku -nd -W 1 QNcdLVw8fHkixm6NNyN6nVwxKek4u7qrioRbQmjxac5TVoTtZuot Dalla coppia pubblica (sulla Testnet): 8

264 $ ku -nt ,even input : ,pari network : Bitcoin testnet coppia pubblica x: coppia pubblica y: x in esadecimale: 79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 y in esadecimale: 483ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 parità y: pari coppia di chiavi come sec: 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 non-compressa: 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f ada7726a3c4655da4fbfc0e1108a8fd17b448a c47d08ffb10d4b8 hash160: 751e76e d454941c45d1b3a323f1433bd6 non-compressa: 91b24bf9f ac687abb035127b1d28a5 Indirizzo bitcoin testnet: mrcdrcybb6j1vrfbwm5hemdjz73fwdbc8r non-compressa: mtoks9v381uahuia3d7vb9gnak8qvmcsme Da hash160: $ ku 751e76e d454941c45d1b3a323f1433bd6 input: 751e76e d454941c45d1b3a323f1433bd6 network : Bitcoin hash160 : 751e76e d454941c45d1b3a323f1433bd6 Indirizzo Bitcoin : 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH Come un indirizzo Dogecoin: 9

265 $ ku -nd 751e76e d454941c45d1b3a323f1433bd6 input : 751e76e d454941c45d1b3a323f1433bd6 network : Dogecoin hash160 : 751e76e d454941c45d1b3a323f1433bd6 Indirizzo Dogecoin : DFpN6QqFfUm3gKNaxN6tNcab1FArL9cZLE Utilità di Transazione - Transaction Utility (TX) L utilità da riga di comando tx mostrerà le transazione in una forma umanamente leggibile, prende le transazioni base dalla cache delle transazioni di pycoin o da servizi web (blockchain.info, blockr.io, e biteasy.com sono attualmente supportati), effettua il merge delle transazioni, aggiunge o rimuove input o output e firma le transazioni. Di seguito puoi trovare altri esempi. Visualizza la famosa "pizza" transaction [PIZZA]: $ tx 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a attenzione: considera impostare la variabile d'ambiente PYCOIN_CACHE_DIR=~/.pycoin_cache per abilitare il caching di transazioni ottenute da servizi web warning: no service providers found for get_tx; consider setting environment variable PYCOIN_SERVICE_PROVIDERS=BLOCKR_IO:BLOCKCHAIN_INFO:BITEASY:BLOCKEXPLORER usage: tx [-h] [-t TRANSACTION_VERSION] [-l LOCK_TIME] [-n NETWORK] [-a] [-i address (indirizzo)] [-f path-to-private-keys (percorso alle chiavi private)] [-g GPG_ARGUMENT (argomento gpg)] [--remove-tx-in tx_in_index_to_delete] [--remove-tx-out tx_out_index_to_delete] [-F transaction-fee] [-u] [-b BITCOIND_URL] [-o path-to-output-file (path al file di output)] argomento [argument...] tx: error: can't find Tx with id (non posso trovare una transazione con id) 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a Oops! Non abbiamo web services impostati. Impostiamoli adesso: $ PYCOIN_CACHE_DIR=~/.pycoin_cache $ PYCOIN_SERVICE_PROVIDERS=BLOCKR_IO:BLOCKCHAIN_INFO:BITEASY:BLOCKEXPLORER $ export PYCOIN_CACHE_DIR PYCOIN_SERVICE_PROVIDERS 10

266 Non è effettuato automaticamente quindi uno strumento da riga di comando non trasmetterà informazioni potenzialmente private riguardo a quale transazione sei interessato a un sito di terza parte. Se questo non ti interessa, potresti mettere queste linee nel tuo.profilo. Proviamo di nuovo: $ tx 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a Version: 1 tx hash 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a 159 bytes TxIn count: 1; TxOut count: 1 Lock time: 0 (valid anytime) Input: 0: (sconosciuta) da 1e133f7de73ac7d074e2746a3d6717dfc99ecaa8e9f9fade2cb8b0b20a5e0441:0 Output: 0: 1CZDM6oTttND6WPdt3D6bydo7DYKzd9Qik receives mbtc Output totale mbtc includndo l'hex dump degli unspent visto che la transazione non è firmata completamente e0ab2b0b82cdefaf9e9a8ca9ec9df17673d6a74e274d0c73ae77d3f131e a a7f26eda c90f87f01ff1ffc76bcd058fe16137e0e63fdb6a35c2d a61e eb73f07c8f209504c84b80f03e30ed8169edd44f80ed17ddf451901ffffffff010010a5d4e a9147ec cae8bded8909cdd6b5e48ba0ab688ac ** impossibile validare la transazione perchè la fonte delle transazioni è attualmente non disponibile L ultima linea appare perchè per validare le firme delle transazioni, ti serve tecnicamente la fonte delle transazioni. Quindi aggiungiamo -a per aggiungere alla transazione informazioni riguardo la fonte: 11

267 $ tx -a 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a attenzione: i suggerimenti riguardo le fee di transazione calcolate e stimate casualmente potrebbero essere non corretti attenzione: le fee di transazione sono più basse del (calcolato casualmente) valore aspettato di 0.1 mbtc, la transazione potrebbe non propagarsi Version: 1 tx hash 49d2adb6e476fa46d8357babf78b1b501fd39e177ac b3f67b17c40c2a 159 bytes TxIn count: 1; TxOut count: 1 Lock time: 0 (valid anytime) Input: 0: 17WFx2GQZUmh6Up2NDNCEDk3deYomdNCfk from 1e133f7de73ac7d074e2746a3d6717dfc99ecaa8e9f9fade2cb8b0b20a5e0441: mbtc sig ok Output: 0: 1CZDM6oTttND6WPdt3D6bydo7DYKzd9Qik receives mbtc Input totali mbtc Output totale mbtc Commissioni totali mbtc e0ab2b0b82cdefaf9e9a8ca9ec9df17673d6a74e274d0c73ae77d3f131e a a7f26eda c90f87f01ff1ffc76bcd058fe16137e0e63fdb6a35c2d a61e eb73f07c8f209504c84b80f03e30ed8169edd44f80ed17ddf451901ffffffff010010a5d4e a9147ec cae8bded8909cdd6b5e48ba0ab688ac tutti i valori delle transazioni in entrata validati Ora, diamo un occhiata agli unspent output per un indirizzo specifico (UTXO). Nel blocco #1, notiamo una transazione coinbase verso 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX. Utilizziamo fetch_unspent per trovare tutti i coin di quest indirizzo: 12

268 $ fetch_unspent 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX a3a6f902a51a2cbebede144e48a88c05e608c2cce a5b a1e2a/0/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/ cea36d008badf5c b191d3239de9582d89b6b452b596f1f1b76347f8cb/31/76a914119b098e2e9 80a229e139a9ed01a469e518e6f2688ac/ ef6b1463f552f675622a5d1fd2c08d6324b f68e767a719e2049e8d/86/76a914119b098e2e9 80a229e139a9ed01a469e518e6f2688ac/10000 a66dddd42f9f2491d3c336ce5527d45cc5c2163aaed3158f81dc054447f447a2/0/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/10000 ffd901679de65d4398de90cefe68d2c3ef073c41f7e8dbec2fb5cd75fe71dfe7/0/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/100 d658ab87cc053b8dbcfd4aa2717fd23cc3edfe90ec75351fadd6a0f7993b461d/5/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/911 36ebe0ca acb12e1474a3859bde0ac84b419ec4ae373e63363ebef731c/1/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/ fd87f9adebb17f4ebb1673da76ff48ad29e64b7afa02fda0f2c14e43d220fe24/0/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/1 dfdf0b375a987f17056e5e919ee6eadd87dad36c09c4016d4a03cea15e5c05e3/1/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/1337 cb2679bfd0a557b2dc0d8a f3fcbe281ca3f3e18d3855aa7ea378fa373/0/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/1337 d6be34ccf6edddc3cf69842dce99fe503bf632ba2c2adb0f95c63f6706ae0c52/1/76a914119b098e2e98 0a229e139a9ed01a469e518e6f2688ac/ e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098/0/410496b538e853519c 726a2c91e61ec11600ae a627c66fb8be7947be63c52da d4e0a604f e bf621e73a82cbf2342c858eeac/

269 Appendix A: Linguaggio di Scripting delle Transazioni: Operatori, Costanti e Simboli Mette un valore nello stack mostra gli operatori per immettere valori sullo stack. Table 1. Mette un valore nello stack Simbolo Valore (hex) Descrizione OP_0 or OP_FALSE 0x00 Un array vuoto è immesso nello stack x01-0x4b Metti i prossimi N byte sullo stack dove N è da 1 a 75 byte OP_PUSHDATA1 0x4c Il prossimo byte script contiene N, immetti i seguenti N byte nello stack OP_PUSHDATA2 0x4d I prossimi due script byte contengono N, metti i seguenti N byte sullo stack OP_PUSHDATA2 0x4d I prossimi quattro script byte contengono N, metti i seguenti N byte sullo stack OP_1NEGATE 0x4f Metti (push) il valore " 1" sullo stack OP_RESERVED 0x50 Halt - Transazione non valida a meno che non sia eseguita la clause Invalid transaction unless found in an unexecuted la clause OP_IF OP_1 or OP_TRUE 0x51 Metti il valore "1" sullo stack OP_2 to OP_16 0x52 to 0x60 Per OP_N, metti il valore "N" sullo stack. Es. OP_2 mette "2" Flow control condizionale mostra gli operatori di flusso condizionale. Table 2. Flow control condizionale Simbolo Valore (hex) Descrizione OP_NOP 0x61 Non eseguire niente 1

270 Simbolo Valore (hex) Descrizione OP_VER 0x62 Interrompi - Transazione Invalida a meno che non sia trovata in una clause OP_IF inaspettata OP_IF 0x63 Esegui le istruzioni continuando se la cima dello stack non è 0 OP_NOTIF 0x64 Esegui le istruzioni continuando se la cima dello stack è 0 OP_VERIF 0x65 Interrompi (Halt) - Transazione non valida OP_VERNOTIF 0x66 Interrompi (Halt) - Transazione non valida OP_ELSE 0x67 Esegui solo se le istruzioni precedenti non erano state eseguite OP_ENDIF 0x68 Finel del blocco OP_IF, OP_NOTIF, OP_ELSE OP_VERIFY 0x69 Controlla la in cima allo stack, interrompi e invalida la transazione se non TRUE OP_RETURN 0x6a Interrompi e invalida la transazione Stack operations mostra gli operatori usati per manipolare lo stack. Table 3. Stack operations Simbolo Valore (hex) Descrizione OP_TOALTSTACK 0x6b Pop (prendi) dell elemento dallo stack e mettilo (push) sullo stack alternativo (altstack) OP_FROMALTSTACK 0x6c Prendi il primo elemento dell altstack e mettilo sullo stack OP_2DROP 0x6d Prendi i primi due elementi dello stack OP_2DUP 0x6e Duplica i due elementi in cima allo stack OP_2DUP 0x6e Duplica i tre elementi in cima allo stack 2

271 Simbolo Valore (hex) Descrizione OP_2OVER 0x70 Copia il terzo e il quarto elemento nello stack e metti le copie in cima OP_2ROT 0x71 Muovi il quinto e il sesto elemento nello stack in cima ad esso OP_2SWAP 0x72 Scambia le due paia di elementi in cima allo stack OP_IFDUP 0x73 Duplica l elemento in cima allo stack se esso non è 0 OP_DEPTH 0x74 Conta gli elementi sullo stack e immetti il valore (del count) risultante sullo stack OP_DROP 0x75 Prendi l elemento in cima allo stack OP_DUP 0x76 Duplica l elemento in cima allo stack OP_NIP 0x77 Prendi il secondo elemento presente nello stack OP_OVER 0x78 Copia il secondo elemento nello stack e mettilo in cima OP_PICK 0x79 Prendi il valore N dalla cima, poi copia l Nesimo elemento in cima allo stack OP_ROLL 0x7a Prendi il valore N dalla cima, poi muovi l Nesimo elemento in cima allo stack OP_ROT 0x7b Ruota i tre elementi in cima allo stack OP_SWAP 0x7c Scambia i tre elementi in cima allo stack OP_TUCK 0x7d Copia l elemento situato in cima e inseriscilo tra l elemento in cima e il secondo elemento. string Operazioni di concatenamento di stringhe mostra gli operatori applicabili sulle stringe. Table 4. string Operazioni di concatenamento di stringhe 3

272 Simbolo Valore (hex) Descrizione OP_CAT 0x7e Disabilitato (concatena i due elementi in cima) OP_SUBSTR 0x7f Disabilitato (ritorna una sottostringa) OP_LEFT 0x80 Disabilitato (ritorna il substring di sinistra) OP_RIGHT 0x81 Disabilitato (ritorna il substring di destra) OP_SIZE 0x82 Calcola la lunghezza della stringa dell elemento in cima e pusha il risultato Aritmetica binaria e condizionali mostra l aritmetica binaria e gli operatori logici booleani Table 5. Aritmetica binaria e condizionali Simbolo Valore (hex) Descrizione OP_INVERT 0x83 Disabilitato (Capovolge i bit dell elemento in cima) OP_AND 0x84 Disabilitato (Booleano AND dei due elementi in cima) OP_OR 0x85 Disabilitato (Booleano OR dei due elementi in cima) OP_XOR 0x86 Disabilitato (Booleano XOR dei due elementi in cima) OP_EQUAL 0x87 Metti TRUE (1) se i due elementi in cima sono esattamente identici, altrimenti metti FALSE (0) OP_EQUALVERIFY 0x88 Come OP_EQUAL, ma esegue OP_VERIFY dopo essersi fermato (halt) se non TRUE OP_RESERVED1 0x89 Halt - Transazione invalida se non trovata in una clause OP_IF inaspettata OP_RESERVED2 0x8a Halt - Transazione invalida se non trovata in una clause OP_IF non eseguita Operatori numerici mostra gli operatori numerici (aritmetici). 4

273 Table 6. Operatori numerici Simbolo Valore (hex) Descrizione OP_1ADD 0x8b Aggiunge 1 all elemento in cima OP_1SUB 0x8c Sottrae 1 dall elemento in cima OP_2MUL 0x8d Disabilitato (moltiplica l elemento in cima per 2) OP_2DIV 0x8e Disabilitato (dividi l elemento in cima per due) OP_NEGATE 0x8f Inverti il segno dell elemento in cima OP_ABS 0x90 Cambia il segno dell elemento in cima in positivo OP_NOT 0x91 Se l elemento in cima è 0 o 1 Booleano, invertilo, altrimenti ritorna 0 OP_0NOTEQUAL 0x92 Se l elemento in cima è 0, ritorna 0, altrimenti ritorna 1 OP_ADD 0x93 Prendi (pop) i due elementi in cima aggiungili e metti il risultato in cima (push) OP_SUB 0x94 Prendi i due elementi in cima, sottrai il primo dal secondo, fai push del risultato OP_MUL 0x95 Disabilitato (moltiplica i due elementi in cima allo stack) OP_DIV 0x96 Disabilitato (dividi il secondo elemento per il primo) OP_MOD 0x97 Disabilitato (resto della divisione tra il secondo elemento per il primo elemento) OP_LSHIFT 0x98 Disabilitato (shifta a sinistra i bit del secondo elemento per i bit indicati dal primo elemento) OP_RSHIFT 0x99 Disabilitato (shifta il secondo elemento a destra per i bit indicati nel primo elemento) OP_BOOLAND 0x9a Booleano AND sui due elementi in cima 5

274 Simbolo Valore (hex) Descrizione OP_BOOLOR 0x9b Booleano OR sui due elementi in cima OP_NUMEQUAL 0x9c Ritorna TRUE se i due elementi in cima sono numeri uguali OP_NUMEQUALVERIFY 0x9d Identico a NUMEQUAL, poi OP_VERIFY per fermare se non è TRUE OP_NUMNOTEQUAL 0x9e Ritorna TRUE se i due elementi in cima non sono numeri uguali OP_LESSTHAN 0x9f Ritorna TRUE se il secondo elemento è inferiore all elemento in cima OP_GREATERTHAN 0xa0 Ritorna TRUE se il secondo elemento è più grande dell elemento in cima OP_LESSTHANOREQUAL 0xa1 Ritorna TRUE se il secondo elemento è inferiore o uguale all elemento in cima OP_GREATERTHANOREQUAL 0xa2 Ritorna TRUE se il secondo elemento è maggiore o uguale all elemento in cima OP_MIN 0xa3 Ritorna il più piccolo dei due elementi in cima OP_MAX 0xa4 Ritorna il più grande dei due elementi in cima OP_WITHIN 0xa5 Ritorna TRUE se il terzo elemento è tra il secondo elemento (o uguale) e il primo elemento Operazioni crittografiche e di hashing mostra gli operatori di funzione crittografica. Table 7. Operazioni crittografiche e di hashing Simbolo Valore (hex) Descrizione OP_RIPEMD160 0xa6 Ritorna l hash RIPEMD160 dell elemento in cima OP_SHA1 0xa7 Ritorna l hash SHA1 dell elemento in cima 6

275 Simbolo Valore (hex) Descrizione OP_SHA256 0xa8 Ritorna l hash SHA256 dell elemento in cima OP_HASH160 0xa9 Ritorna l hash RIPEMD160(SHA256(x)) dell elemento in cima OP_HASH256 0xaa Ritorna l hash SHA256(SHA256(x)) dell elemento in cima OP_CODESEPARATOR 0xab Segna l inizio di un dato signature-checked (controllato da firma) OP_CHECKSIG 0xac Pop a public key and signature and validate the signature for the transaction s hashed data, return TRUE if matching OP_CHECKSIGVERIFY 0xad Uguale a CHECKSIG, inoltre fa si che OP_VERIFY si fermi (halt) se non TRUE OP_CHECKMULTISIG 0xae Esegui CHECKSIG per ogni coppia di firma e public key fornita. Tutte devono corrispondere. Un bug nell implementazione fa il pop di un valore extra, usa il prefisso NO_OP come workaround. OP_CHECKMULTISIGVERIFY 0xaf Uguale a CHECKMULTISIG, inoltre fa si che OP_VERIFY si interrompa (halt) se non TRUE Non-operatori mostra simboli nonoperator Table 8. Non-operatori Simbolo Valore (hex) Descrizione OP_NOP1-OP_NOP10 0xb0-0xb9 Non fa niente, ignorato OP code riservati per uso interno dal parser mostra i codici operatori riservati all uso per lo script interno di parsing. Table 9. OP code riservati per uso interno dal parser 7

276 Simbolo Valore (hex) Descrizione OP_SMALLDATA 0xf9 Rappresenta un campo dati piccolo OP_SMALLINTEGER 0xfa Rappresenta un campo dati per un intero piccolo OP_PUBKEYS 0xfb Rappresenta i campi della public key OP_PUBKEYHASH 0xfd Rappresenta un campo per un hash di una chiave pubblica OP_PUBKEY 0xfe Rappresenta un campo per una chiave pubblica OP_INVALIDOPCODE 0xff Rappresenta un qualsiasi OP code non attualmente assegnato 8

Compatibilità del Portale Piaggio con Internet Explorer 10 e 11. Internet Explorer 10

Compatibilità del Portale Piaggio con Internet Explorer 10 e 11. Internet Explorer 10 Italiano: Explorer 10 pagina 1, Explorer 11 pagina 2 English: Explorer 10 page 3 and 4, Explorer 11 page 5. Compatibilità del Portale Piaggio con Internet Explorer 10 e 11 Internet Explorer 10 Con l introduzione

Подробнее

Portale Materiali Grafiche Tamburini. Grafiche Tamburini Materials Portal

Portale Materiali Grafiche Tamburini. Grafiche Tamburini Materials Portal Portale Materiali Grafiche Tamburini Documentazione utente italiano pag. 2 Grafiche Tamburini Materials Portal English user guide page 6 pag. 1 Introduzione Il Portale Materiali è il Sistema Web di Grafiche

Подробнее

Una breve introduzione ai Bitcoin. @FlavioGiobergia

Una breve introduzione ai Bitcoin. @FlavioGiobergia Una breve introduzione ai Bitcoin Bitcoin: cos'è? Bitcoin è una moneta decentralizzata: non esiste alcun potere centrale in grado di controllarla. Al suo posto, esiste una rete di peers che gestisce tutte

Подробнее

WELCOME. Go to the link of the official University of Palermo web site www.unipa.it; Click on the box on the right side Login unico

WELCOME. Go to the link of the official University of Palermo web site www.unipa.it; Click on the box on the right side Login unico WELCOME This is a Step by Step Guide that will help you to register as an Exchange for study student to the University of Palermo. Please, read carefully this guide and prepare all required data and documents.

Подробнее

www.aylook.com -Fig.1-

www.aylook.com -Fig.1- 1. RAGGIUNGIBILITA DI AYLOOK DA REMOTO La raggiungibilità da remoto di Aylook è gestibile in modo efficace attraverso una normale connessione ADSL. Si presentano, però, almeno due casi: 1.1 Aylook che

Подробнее

Dropbox di classe. É un servizio internet fornito gratuitamente (funzioni base).

Dropbox di classe. É un servizio internet fornito gratuitamente (funzioni base). Dropbox di classe Lo scopo del servizio Dropbox di classe è quello di far conoscere ai docenti del nostro istituto il funzionamento di un sistema di Cloud Storage, pronto e facile da usare, per esplorare

Подробнее

API e socket per lo sviluppo di applicazioni Web Based

API e socket per lo sviluppo di applicazioni Web Based API e socket per lo sviluppo di applicazioni Web Based Cosa sono le API? Consideriamo il problema di un programmatore che voglia sviluppare un applicativo che faccia uso dei servizi messi a disposizione

Подробнее

U Corso di italiano, Lezione Diciannove

U Corso di italiano, Lezione Diciannove 1 U Corso di italiano, Lezione Diciannove U Al telefono: M On the phone: U Al telefono: U Pronto Elena, come stai? M Hello Elena, how are you? U Pronto Elena, come stai? D Ciao Paolo, molto bene, grazie.

Подробнее

Introduzione a Bitcoin. Marco Polci [email protected]

Introduzione a Bitcoin. Marco Polci mpolci@gmail.com Introduzione a Bitcoin Marco Polci [email protected] Portafoglio Per Windows e Mac OSX: Electrum https://www.electrum.org/download.html Procurarsi un foglio di carta e una penna per il «backup» Per smartphone:

Подробнее

Guida al sistema. Dott. Enea Belloni

Guida al sistema. Dott. Enea Belloni Sistema Gestionale Voucher Guida al sistema Dott. Enea Belloni Sommario della presentazione Il sistema informatico per la gestione delle domande L utente presentatore: diritti e responsabilità La pagina

Подробнее

INFORMATIVA SULLA PRIVACY DEL SITO WEB THERMOPLAY TEAM

INFORMATIVA SULLA PRIVACY DEL SITO WEB THERMOPLAY TEAM INFORMATIVA SULLA PRIVACY DEL SITO WEB THERMOPLAY TEAM La vostra privacy è importante per THERMOPLAY TEAM. Questa informativa sulla privacy fornisce informazioni sui dati personali che THERMOPLAY TEAM

Подробнее

Guida alla registrazione on-line di un NovaSun Log

Guida alla registrazione on-line di un NovaSun Log Guida alla registrazione on-line di un NovaSun Log Revisione 4.1 23/04/2012 pag. 1 di 16 Contenuti Il presente documento è una guida all accesso e all utilizzo del pannello di controllo web dell area clienti

Подробнее

PROMUOVERSI MEDIANTE INTERNET di Riccardo Polesel. 1. Promuovere il vostro business: scrivere e gestire i contenuti online» 15

PROMUOVERSI MEDIANTE INTERNET di Riccardo Polesel. 1. Promuovere il vostro business: scrivere e gestire i contenuti online» 15 Indice Introduzione pag. 9 Ringraziamenti» 13 1. Promuovere il vostro business: scrivere e gestire i contenuti online» 15 1. I contenuti curati, interessanti e utili aiutano il business» 15 2. Le aziende

Подробнее

ISLL Papers The Online Collection of the Italian Society for Law and Literature http://www.lawandliterature.org/index.php?

ISLL Papers The Online Collection of the Italian Society for Law and Literature http://www.lawandliterature.org/index.php? The Online Collection of the Italian Society for Law and Literature http://www.lawandliterature.org/index.php?channel=papers ISLL - ITALIAN SOCIETY FOR LAW AND LITERATURE ISSN 2035-553X Submitting a Contribution

Подробнее

Introduzione Kerberos. Orazio Battaglia

Introduzione Kerberos. Orazio Battaglia Orazio Battaglia Il protocollo Kerberos è stato sviluppato dal MIT (Massachusetts Institute of Tecnology) Iniziato a sviluppare negli anni 80 è stato rilasciato come Open Source nel 1987 ed è diventato

Подробнее

EMAIL MARKETING CHE FUNZIONA PDF

EMAIL MARKETING CHE FUNZIONA PDF EMAIL MARKETING CHE FUNZIONA PDF ==> Download: EMAIL MARKETING CHE FUNZIONA PDF EMAIL MARKETING CHE FUNZIONA PDF - Are you searching for Email Marketing Che Funziona Books? Now, you will be happy that

Подробнее

Innanzitutto andiamo sul sito http://www.dropbox.com/ ed eseguiamo il download del programma cliccando su Download Dropbox.

Innanzitutto andiamo sul sito http://www.dropbox.com/ ed eseguiamo il download del programma cliccando su Download Dropbox. Oggi parlerò di qualcosa che ha a che fare relativamente con la tecnica fotografica, ma che ci può dare una mano nella gestione dei nostri archivi digitali, soprattutto nel rapporto professionale con altre

Подробнее

Capitolo 4 Pianificazione e Sviluppo di Web Part

Capitolo 4 Pianificazione e Sviluppo di Web Part Capitolo 4 Pianificazione e Sviluppo di Web Part Questo capitolo mostra come usare Microsoft Office XP Developer per personalizzare Microsoft SharePoint Portal Server 2001. Spiega come creare, aggiungere,

Подробнее

1) GESTIONE DELLE POSTAZIONI REMOTE

1) GESTIONE DELLE POSTAZIONI REMOTE IMPORTAZIONE ESPORTAZIONE DATI VIA FTP Per FTP ( FILE TRANSFER PROTOCOL) si intende il protocollo di internet che permette di trasferire documenti di qualsiasi tipo tra siti differenti. Per l utilizzo

Подробнее

ISTR- XX Uso del Blog http://telelavoro.tpk.it

ISTR- XX Uso del Blog http://telelavoro.tpk.it Pagina 1 di 5 1.CAMPO DI APPLICAZIONE Ai dipendenti che fanno parte del progetto di Telelavoro è stato attivato un utente al Blog situato al sito http://telelavoro.tpk.it, che permette una veloce ed efficace

Подробнее

U Corso di italiano, Lezione Quindici

U Corso di italiano, Lezione Quindici 1 U Corso di italiano, Lezione Quindici U Buongiorno, anche in questa lezione iniziamo con qualche dialogo formale M Good morning, in this lesson as well, let s start with some formal dialogues U Buongiorno,

Подробнее

Brand Il primo corso per gli imprenditori che vogliono imparare l arma segreta del Brand Positioning Introduzione

Brand Il primo corso per gli imprenditori che vogliono imparare l arma segreta del Brand Positioning Introduzione Il primo corso per gli imprenditori che vogliono imparare l arma segreta del Brand Positioning Un corso di Marco De Veglia Brand Positioning: la chiave segreta del marketing Mi occupo di Brand Positioning

Подробнее

Ti presentiamo due testi che danno informazioni ai cittadini su come gestire i propri

Ti presentiamo due testi che danno informazioni ai cittadini su come gestire i propri Unità 11 Questione di soldi CHIAVI In questa unità imparerai: come spedire i soldi all estero come usare il bancomat gli aggettivi e i pronomi dimostrativi questo e quello a costruire frasi negative con

Подробнее

ammesso solo con il tuo consenso. Le modifiche apportate hanno lo scopo di semplificare il controllo di quali

ammesso solo con il tuo consenso. Le modifiche apportate hanno lo scopo di semplificare il controllo di quali CHE COSA SONO I COOKIES E COME LI UTILIZZIAMO Un cookie è un semplice file di testo che viene memorizzato sul tuo computer o dispositivo mobile dal server di un sito web e che solo quel server sarà in

Подробнее

User Guide Guglielmo SmartClient

User Guide Guglielmo SmartClient User Guide Guglielmo SmartClient User Guide - Guglielmo SmartClient Version: 1.0 Guglielmo All rights reserved. All trademarks and logos referenced herein belong to their respective companies. -2- 1. Introduction

Подробнее

Pagamento e Completamento del Flusso

Pagamento e Completamento del Flusso Pagamento e Completamento del Flusso Login Membro Visualizza l Attestazione delle Azioni Seleziona Opzione Attestazione Invia un Certificato Cartaceo di Proprietà Crea un Account di Negoziazione Azioni

Подробнее

Solutions in motion.

Solutions in motion. Solutions in motion. Solutions in motion. SIPRO SIPRO presente sul mercato da quasi trent anni si colloca quale leader italiano nella progettazione e produzione di soluzioni per il motion control. Porsi

Подробнее

Il calendario di Windows Vista

Il calendario di Windows Vista Il calendario di Windows Vista Una delle novità introdotte in Windows Vista è il Calendario di Windows, un programma utilissimo per la gestione degli appuntamenti, delle ricorrenze e delle attività lavorative

Подробнее

COSA FARE APPENA ACQUISTATA UNA SMARTBOARD TM

COSA FARE APPENA ACQUISTATA UNA SMARTBOARD TM COSA FARE APPENA ACQUISTATA UNA SMARTBOARD TM Una volta acquistata una Lavagna Interattiva Multimediale SMARTBoard TM, è necessario effettuare una procedura di registrazione al fine di:. Estendere la garanzia

Подробнее

Come funziona il WWW. Architettura client-server. Web: client-server. Il protocollo

Come funziona il WWW. Architettura client-server. Web: client-server. Il protocollo Come funziona il WWW Il funzionamento del World Wide Web non differisce molto da quello delle altre applicazioni Internet Anche in questo caso il sistema si basa su una interazione tra un computer client

Подробнее

Guida Rapida all uso del License Manager di ROCKEY4Smart (V. 1.0.10.724)

Guida Rapida all uso del License Manager di ROCKEY4Smart (V. 1.0.10.724) Guida Rapida all uso del License Manager di ROCKEY4Smart (V. 1.0.10.724) Procedo con un esempio: voglio proteggere una applicazione (nell esempio Blocco Note di Windows: notepad.exe) per distribuirla con

Подробнее

Il sistema monetario

Il sistema monetario Il sistema monetario Premessa: in un sistema economico senza moneta il commercio richiede la doppia coincidenza dei desideri. L esistenza del denaro rende più facili gli scambi. Moneta: insieme di tutti

Подробнее

Istruzioni per l installazione del software per gli esami ICoNExam (Aggiornate al 15/01/2014)

Istruzioni per l installazione del software per gli esami ICoNExam (Aggiornate al 15/01/2014) Istruzioni per l installazione del software per gli esami ICoNExam (Aggiornate al 15/01/2014) Il software per gli esami ICON può essere eseguito su qualunque computer dotato di Java Virtual Machine aggiornata.

Подробнее

UNIVERSITÀ DEGLI STUDI DI TORINO

UNIVERSITÀ DEGLI STUDI DI TORINO STEP BY STEP INSTRUCTIONS FOR COMPLETING THE ONLINE APPLICATION FORM Enter the Unito homepage www.unito.it and click on Login on the right side of the page. - Tel. +39 011 6704425 - e-mail [email protected]

Подробнее

Coin Generation Come versare e prelevare (V.3 - aggiornata al 12 settembre 2013)

Coin Generation Come versare e prelevare (V.3 - aggiornata al 12 settembre 2013) Coin Generation Come versare e prelevare (V.3 - aggiornata al 12 settembre 2013) Questa breve guida ha lo scopo di fare chiarezza sui metodi attivi al momento per versare e prelevare da Coin Generation,

Подробнее

Introduzione ai Web Services Alberto Polzonetti

Introduzione ai Web Services Alberto Polzonetti PROGRAMMAZIONE di RETE A.A. 2003-2004 Corso di laurea in INFORMATICA Introduzione ai Web Services [email protected] Introduzione al problema della comunicazione fra applicazioni 2 1 Il Problema

Подробнее

COME CREARE UNA COMUNICAZIONE / NEWSLETTER

COME CREARE UNA COMUNICAZIONE / NEWSLETTER COME CREARE UNA COMUNICAZIONE / NEWSLETTER Benvenuti nella MINI GUIDA di Centrico per la creazione di una nuova Comunicazione o Newsletter. Grazie a questa guida, potrai creare delle comunicazioni ad hoc

Подробнее

Questa guida è stata redatta per gli insegnanti amministratori che entrano in TwinSpace per la prima volta. Vi aiuterà a:

Questa guida è stata redatta per gli insegnanti amministratori che entrano in TwinSpace per la prima volta. Vi aiuterà a: Benvenuti Guida a TwinSpace Questa guida è stata redatta per gli insegnanti amministratori che entrano in TwinSpace per la prima volta. Vi aiuterà a: - Accedere al vostro TwinSpace - Modificare il vostro

Подробнее

Email Marketing Vincente

Email Marketing Vincente Email Marketing Vincente (le parti in nero sono disponibili nella versione completa del documento): Benvenuto in Email Marketing Vincente! L email marketing è uno strumento efficace per rendere più semplice

Подробнее

EUROCONSULTANCY-RE. Privacy Policy

EUROCONSULTANCY-RE. Privacy Policy Privacy Policy EUROCONSULTANCY-RE di Concept Design 95 Ltd Registered in England - Co. Reg. no. 3148248 - VAT no.690052547 (GB) No. Iscrizione Camera di Commercio di Milano (REA) 1954902 Codici Fiscale

Подробнее

Novità di Access 2010

Novità di Access 2010 2 Novità di Access 2010 In questo capitolo: Gestire le impostazioni e i file di Access nella visualizzazione Backstage Personalizzare l interfaccia utente di Access 2010 Creare database utilizzando modelli

Подробнее

Network Services Location Manager. Guida per amministratori di rete

Network Services Location Manager. Guida per amministratori di rete apple Network Services Location Manager Guida per amministratori di rete Questo documento illustra le caratteristiche di Network Services Location Manager e spiega le configurazioni di rete per sfruttarne

Подробнее

Informazioni di identificazione personali

Informazioni di identificazione personali Questa Privacy Policy disciplina il modo in cui GIANGI SRL raccoglie, utilizza, conserva e divulga le informazioni raccolte dagli utenti (ciascuno, un Utente ) del sito web www.mamasunpesaro.it ( Sito

Подробнее

Nautilus Installazione Aggiornato a versione 2.4.1092

Nautilus Installazione Aggiornato a versione 2.4.1092 Nautilus Installazione Aggiornato a versione 2.4.1092 IMPORTANTE: NON INSERIRE LA CHIAVE USB DI LICENZA FINO A QUANDO RICHIESTO NOTA: se sul vostro computer è già installato Nautilus 2.4, è consigliabile

Подробнее

Guida informatica per l associazione #IDEA

Guida informatica per l associazione #IDEA Guida informatica per l associazione #IDEA Questa guida vi spiegherà come utilizzare al meglio gli strumenti informatici che utilizza l associazione #IDEA in modo da facilitare il coordinamento con tutti

Подробнее

Università degli Studi di Messina

Università degli Studi di Messina Università degli Studi di Messina Guida alla Rendicontazione on-line delle Attività del Docente Versione della revisione: 2.02/2013-07 A cura di: Fabio Adelardi Università degli studi di Messina Centro

Подробнее

Social Network. Marco Battini

Social Network. Marco Battini Social Network Marco Battini Luoghi immateriali che grazie all elettricità si sono trasformati in realtà oggettiva frequentata da milioni di persone nel mondo. Luoghi che ti permettono di essere sempre

Подробнее

informazioni che si può leggere bene, chiaro con caratteri di scrittura simile a quelli usati nella stampa, ma scritti a mano chi riceve una lettera

informazioni che si può leggere bene, chiaro con caratteri di scrittura simile a quelli usati nella stampa, ma scritti a mano chi riceve una lettera Unità 12 Inviare una raccomandata In questa unità imparerai: a comprendere testi che danno informazioni su come inviare una raccomandata parole relative alle spedizioni postali e all invio di una raccomandata

Подробнее

La prima piattaforma per chi insegna e per chi impara l italiano

La prima piattaforma per chi insegna e per chi impara l italiano La prima piattaforma per chi insegna e per chi impara l italiano Semplice Efficace Gratuita Molto più di una piattaforma! i-d-e-e.it è in realtà una multipiattaforma didattica, la prima appositamente dedicata

Подробнее

Come usare TwinSpace. Benvenuti in TwinSpace!

Come usare TwinSpace. Benvenuti in TwinSpace! Come usare TwinSpace Benvenuti in TwinSpace! TwinSpace è il forum per la comunicazione e la comunicazione nell ambito dei partenariati etwinning. Tutte le scuole possono accedere al proprio TwinSpace personale

Подробнее

Il cloud per la tua azienda.

Il cloud per la tua azienda. Il cloud per la tua azienda. Questo è Microsoft Cloud Ogni azienda è unica. Dalla sanità alla vendita al dettaglio, alla produzione o alla finanza, non esistono due aziende che operano nello stesso modo.

Подробнее

Al giorno d oggi, i sistemi per la gestione di database

Al giorno d oggi, i sistemi per la gestione di database Introduzione Al giorno d oggi, i sistemi per la gestione di database implementano un linguaggio standard chiamato SQL (Structured Query Language). Fra le altre cose, il linguaggio SQL consente di prelevare,

Подробнее

Scopo della lezione. Informatica. Informatica - def. 1. Informatica

Scopo della lezione. Informatica. Informatica - def. 1. Informatica Scopo della lezione Informatica per le lauree triennali LEZIONE 1 - Che cos è l informatica Introdurre i concetti base della materia Definire le differenze tra hardware e software Individuare le applicazioni

Подробнее

Il concetto di Dare/Avere

Il concetto di Dare/Avere NISABA SOLUTION Il concetto di Dare/Avere Comprendere i fondamenti delle registrazioni in Partita Doppia Sara Mazza Edizione 2012 Sommario Introduzione... 3 Il Bilancio d Esercizio... 4 Stato Patrimoniale...

Подробнее

MODELLO CLIENT/SERVER. Gianluca Daino Dipartimento di Ingegneria dell Informazione Università degli Studi di Siena [email protected]

MODELLO CLIENT/SERVER. Gianluca Daino Dipartimento di Ingegneria dell Informazione Università degli Studi di Siena daino@unisi.it MODELLO CLIENT/SERVER Gianluca Daino Dipartimento di Ingegneria dell Informazione Università degli Studi di Siena [email protected] POSSIBILI STRUTTURE DEL SISTEMA INFORMATIVO La struttura di un sistema informativo

Подробнее

Abitantionline. Il social network per la casa e il costruito. Per chi è Cosa offre Lancio e partner. creato

Abitantionline. Il social network per la casa e il costruito. Per chi è Cosa offre Lancio e partner. creato Abitantionline Il social network per la casa e il costruito Abitantionline mette in contatto tutte le professioni e i servizi che ruotano attorno al mondo della casa. Fa parlare, conoscere e discutere.

Подробнее

Vivere meglio ed aiutare il proprio territorio

Vivere meglio ed aiutare il proprio territorio ORGANIZZARSI PER VIVERE MEGLIO Conoscere GAŠ-web per: Gestire al meglio un Gruppo di Acquisto ottimizzare le risorse a disposizione risparmiare il proprio tempo Vivere meglio ed aiutare il proprio territorio

Подробнее

Gui Gu d i a d ra r p a i p d i a V d o a d f a one Int fone In e t r e net rnet Box Key Mini

Gui Gu d i a d ra r p a i p d i a V d o a d f a one Int fone In e t r e net rnet Box Key Mini Guida rapida Vodafone Internet Key Box Mini Ideato per Vodafone QSG_VMCLite_v31_10-2007_e172_IT.1 1 10/10/07 14:39:10 QSG_VMCLite_v31_10-2007_e172_IT.2 2 10/10/07 14:39:11 Benvenuti nel mondo della connessione

Подробнее

Active Directory. Installatore LAN. Progetto per le classi V del corso di Informatica

Active Directory. Installatore LAN. Progetto per le classi V del corso di Informatica Installatore LAN Progetto per le classi V del corso di Informatica Active Directory 26/02/08 Installatore LAN - Prof.Marco Marchisotti 1 Agli albori delle reti...... nelle prime LAN era facile individuare

Подробнее

Express Import system

Express Import system Express Import system Manuale del destinatario Sistema Express Import di TNT Il sistema Express Import di TNT Le consente di predisporre il ritiro di documenti, pacchi o pallet in 168 paesi con opzione

Подробнее

Artigiani di Podcast. Lezione del 8 febbraio 2012. Fabio P. Corti

Artigiani di Podcast. Lezione del 8 febbraio 2012. Fabio P. Corti Artigiani di Podcast Lezione del 8 febbraio 2012 Che cosa è un podcast? Un podcast è un programma a episodi distribuito via internet usando un protocollo specifico chiamato RSS. Gli episodi dei podcast

Подробнее

GUIDA AL SITO DELLE RIPARAZIONI BARWARE SOMMARIO

GUIDA AL SITO DELLE RIPARAZIONI BARWARE SOMMARIO GUIDA AL SITO DELLE RIPARAZIONI BARWARE SOMMARIO Introduzione...2 1. Registrazione al sito delle riparazioni...2 2. Login e Home page...6 3. Assistenza...8 3a. Nuova richiesta di riparazione...8 3b. Lista

Подробнее

da 2 a 5 giocatori, dai 10 anni in su, durata 30 minuti

da 2 a 5 giocatori, dai 10 anni in su, durata 30 minuti da 2 a 5 giocatori, dai 10 anni in su, durata 30 minuti OBIETTIVO Il vincitore è colui che, dopo due round di gioco, delle sue 11 ordinazioni, ne ha consegnate il maggior numero. CONTENUTO DELLA SCATOLA

Подробнее

CONSIGLI PER POTENZIARE L APPRENDIMENTO DELLA LINGUA

CONSIGLI PER POTENZIARE L APPRENDIMENTO DELLA LINGUA CONSIGLI PER POTENZIARE L APPRENDIMENTO DELLA LINGUA Possiamo descrivere le strategie di apprendimento di una lingua straniera come traguardi che uno studente si pone per misurare i progressi nell apprendimento

Подробнее

IT Cloud Service. Semplice - accessibile - sicuro - economico

IT Cloud Service. Semplice - accessibile - sicuro - economico IT Cloud Service Semplice - accessibile - sicuro - economico IT Cloud Service - Cos è IT Cloud Service è una soluzione flessibile per la sincronizzazione dei file e la loro condivisione. Sia che si utilizzi

Подробнее

Biblioteca di Cervia NOZIONI BASE DI INFORMATICA

Biblioteca di Cervia NOZIONI BASE DI INFORMATICA Biblioteca di Cervia NOZIONI BASE DI INFORMATICA NOZIONI DI INFORMATICA Il PC è composto solitamente di tre parti principali: - Il Case, ovvero il contenitore del cuore del computer, da qui si accende

Подробнее

lettera raccomandata. Ecco alcune parole ed espressioni che possono aiutarti a capire meglio il testo.

lettera raccomandata. Ecco alcune parole ed espressioni che possono aiutarti a capire meglio il testo. Unità 12 Inviare una raccomandata CHIAVI In questa unità imparerai: a comprendere testi che danno informazioni su come inviare una raccomandata parole relative alle spedizioni postali e all invio di una

Подробнее

Introduzione alla programmazione in C

Introduzione alla programmazione in C Introduzione alla programmazione in C Testi Consigliati: A. Kelley & I. Pohl C didattica e programmazione B.W. Kernighan & D. M. Ritchie Linguaggio C P. Tosoratti Introduzione all informatica Materiale

Подробнее

idc IDC INTELLIGENT DIGITAL CASH LA SOLUZIONE CRITTOGRAFICA DI MONETA ELETTRONICA REGOLAMENTATA

idc IDC INTELLIGENT DIGITAL CASH LA SOLUZIONE CRITTOGRAFICA DI MONETA ELETTRONICA REGOLAMENTATA IDC INTELLIGENT DIGITAL CASH LA SOLUZIONE CRITTOGRAFICA DI MONETA ELETTRONICA REGOLAMENTATA Abstract POTENZA DI CALCOLO: utilizzo della crittografia nell implementazione di meccanismi di pagamento in cui

Подробнее

(fonte: http://www.agenziaentrate.gov.it/wps/content/nsilib/nsi/documentazione/fatturazione +elettronica+pa+-+regole+generali/ )

(fonte: http://www.agenziaentrate.gov.it/wps/content/nsilib/nsi/documentazione/fatturazione +elettronica+pa+-+regole+generali/ ) Fattura elettronica: cos è? È un tipo di fattura in formato XML e non un semplice.pdf o scansione della solita fattura. Il formato XML garantisce la conversione dei file per l elaborazione con i principali

Подробнее

Guida alla compilazione on-line delle domande di Dote Scuola A.S. 2014-2015 - per le Famiglie INDICE

Guida alla compilazione on-line delle domande di Dote Scuola A.S. 2014-2015 - per le Famiglie INDICE Guida alla compilazione on-line delle domande di Dote Scuola A.S. 2014-2015 - per le Famiglie INDICE Introduzione... 2 Riconoscimento del soggetto richiedente da parte del sistema... 2 Elenco dei servizi

Подробнее

Come visualizzare un dispositivo EZVIZ via web browser / Client mobile / client software ivms-4200

Come visualizzare un dispositivo EZVIZ via web browser / Client mobile / client software ivms-4200 Come visualizzare un dispositivo EZVIZ via web browser / Client mobile / client software ivms-4200 1 Indice Nota Importante... 3 Come abilitare un dispositivo prima dell attivazione... 3 Registrare e visualizzare

Подробнее

ATOLLO BACKUP GUIDA INSTALLAZIONE E CONFIGURAZIONE

ATOLLO BACKUP GUIDA INSTALLAZIONE E CONFIGURAZIONE ATOLLO BACKUP GUIDA INSTALLAZIONE E CONFIGURAZIONE PREMESSA La presente guida è da considerarsi come aiuto per l utente per l installazione e configurazione di Atollo Backup. La guida non vuole approfondire

Подробнее

Corso di Informatica

Corso di Informatica Corso di Informatica Modulo T2 1 Sistema software 1 Prerequisiti Utilizzo elementare di un computer Significato elementare di programma e dati Sistema operativo 2 1 Introduzione In questa Unità studiamo

Подробнее

Bitcoin e Cash Out. 1 a parte Aspetti Tecnici e Investigativi (Paolo Dal Checco)

Bitcoin e Cash Out. 1 a parte Aspetti Tecnici e Investigativi (Paolo Dal Checco) 1 a parte Aspetti Tecnici e Investigativi (), Consulente Informatico Forense Stefano Capaccioli, Dottore Commercialista Roma, 17 dicembre 2015 - GIPAF Gruppo di Lavoro Interdisciplinare per la Prevenzione

Подробнее

WELCOME UNIPA REGISTRATION:

WELCOME UNIPA REGISTRATION: WELCOME This is a Step by Step Guide that will help you to register as an Exchange for study student to the University of Palermo. Please, read carefully this guide and prepare all required data and documents.

Подробнее

Modulo. Programmiamo in Pascal. Unità didattiche COSA IMPAREREMO...

Modulo. Programmiamo in Pascal. Unità didattiche COSA IMPAREREMO... Modulo A Programmiamo in Pascal Unità didattiche 1. Installiamo il Dev-Pascal 2. Il programma e le variabili 3. Input dei dati 4. Utilizziamo gli operatori matematici e commentiamo il codice COSA IMPAREREMO...

Подробнее

Cookie: è scaduto il 2 giugno il termine per mettersi in regola con le prescrizioni del Garante

Cookie: è scaduto il 2 giugno il termine per mettersi in regola con le prescrizioni del Garante 1 di 5 04/06/2015 13:17 Cookie: è scaduto il 2 giugno il termine per mettersi in regola con le prescrizioni del Garante Stampa Invia per mail Condividi Come previsto dal Provvedimento dell'8 maggio 2014,

Подробнее

Internet e posta elettronica. A cura di Massimiliano Buschi

Internet e posta elettronica. A cura di Massimiliano Buschi Internet e posta elettronica A cura di Massimiliano Buschi Concetti fondamentali Internet www Tcp/ip Browser Terminologia Esistono un sacco di termini con cui bisogna famigliarizzare http url Link Isp

Подробнее

Guida all utilizzo di Moodle per gli studenti

Guida all utilizzo di Moodle per gli studenti Guida all utilizzo di Moodle per gli studenti 1 Premessa La piattaforma utilizzata per le attività a distanza è Moodle, un software per la gestione di corsi online. Dal punto di vista dello studente, si

Подробнее

"Trasforma Immediatamente i tuoi semplici documenti in Pagine Web generatrici di guadagno con Google Adsense!"

Trasforma Immediatamente i tuoi semplici documenti in Pagine Web generatrici di guadagno con Google Adsense! "Trasforma Immediatamente i tuoi semplici documenti in Pagine Web generatrici di guadagno con Google Adsense!" Questo Semplice Software ti permette di Costruire Centinaia Di Pagine Web Gratuitamente! Caro

Подробнее

Posta elettronica per gli studenti Email for the students

Posta elettronica per gli studenti Email for the students http://www.uninettunouniverstiy.net Posta elettronica per gli studenti Email for the students Ver. 1.0 Ultimo aggiornamento (last update): 10/09/2008 13.47 Informazioni sul Documento / Information on the

Подробнее

Il tutor è a disposizione per ogni chiarimento

Il tutor è a disposizione per ogni chiarimento INDICAZIONI PER ESSERE OPERATIVI Alcune istruzioni per rendervi la vita più facile e accedere alle risorse del percorso online di Sociologia intuitivamente Il tutor è a disposizione per ogni chiarimento

Подробнее

IL CODICE UNICO DI PROGETTO (CUP) FAQ PER L AREA RICERCA

IL CODICE UNICO DI PROGETTO (CUP) FAQ PER L AREA RICERCA IL CODICE UNICO DI PROGETTO (CUP) FAQ PER L AREA RICERCA A. CUP: QUANDO INIZIA, QUANDO FINISCE E COME 1) Quando si chiede il CUP? Il Soggetto responsabile (ovvero titolare) deve chiedere il codice dopo

Подробнее

3 modi per risparmiare soldi sulle bollette di elettricità e gas. Italiano Semplice Aprile 2015. Italian

3 modi per risparmiare soldi sulle bollette di elettricità e gas. Italiano Semplice Aprile 2015. Italian 3 modi per risparmiare soldi sulle bollette di elettricità e gas Italiano Semplice Aprile 2015 Italian Questo opuscolo ti spiegherà 3 modi per risparmiare sulle bollette dell elettricità e del gas. 1.

Подробнее

Guida alla configurazione Configuration Guide

Guida alla configurazione Configuration Guide Guida alla configurazione Configuration Guide Configurazione telecamere IP con DVR analogici, compatibili IP IP cameras configuration with analog DVR, IP compatible Menu principale: Fare clic con il pulsante

Подробнее

Le biblioteche raccontate a mia fi glia

Le biblioteche raccontate a mia fi glia La collana Conoscere la biblioteca si rivolge direttamente agli utenti delle biblioteche per spiegare, con un linguaggio semplice, il ruolo e i diversi aspetti di questo servizio. Per tali caratteristiche

Подробнее

DOCUMENTO ESERCITAZIONE ONENOTE. Utilizzare Microsoft Offi ce OneNote 2003: esercitazione rapida

DOCUMENTO ESERCITAZIONE ONENOTE. Utilizzare Microsoft Offi ce OneNote 2003: esercitazione rapida Utilizzare Microsoft Offi ce OneNote 2003: esercitazione rapida MICROSOFT OFFICE ONENOTE 2003 AUMENTA LA PRODUTTIVITÀ CONSENTENDO AGLI UTENTI L ACQUISIZIONE COMPLETA, L ORGANIZZAZIONE EFFICIENTE E IL RIUTILIZZO

Подробнее

Esempio 1: CarMatch. Direzione centrale Sedi centrali per ogni paese Concessionarie locali di franchising UML 2

Esempio 1: CarMatch. Direzione centrale Sedi centrali per ogni paese Concessionarie locali di franchising UML 2 Esempio 1: CarMatch CarMatch è una società di franchising fondata con lo scopo di promuovere il car sharing CarMatch fornisce un servizio per i potenziali condivisori di automobili cercando di abbinare

Подробнее

Strategie e Operatività nei processi di backup e restore

Strategie e Operatività nei processi di backup e restore Strategie e Operatività nei processi di backup e restore ver. 3.0-2014 Linee Guida + Do You Backup Your Invaluable Data? Now You Can with DuBackup! NSC s.r.l. Tutti i diritti riservati. Tutti i materiali

Подробнее