blockchain

package
v0.0.0-...-d1a22ea Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 28, 2020 License: ISC Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Coin valore in satoshis
	Coin = 100000000 //10^8
	// MaxMoney massimo ammontare
	MaxMoney = 21000000 * Coin
)
View Source
const Bits = 0x1d00ffff // in bitcoin il blocco genesis ha nBits = 0x1d00ffff rappresentazione Compat

Bits incrementando la difficoltà aumentano il numero di bytes a 0 e sarà più difficile trovare un hash inferiore al numero dato [come calcolare nBits](https://bitcoin.stackexchange.com/questions/2924/how-to-calculate-new-bits-value)

Variables

This section is empty.

Functions

func CalculateNextWorkRequired

func CalculateNextWorkRequired(block *Block) uint

CalculateNextWorkRequired calcola la difficoltà

func CompactToBig

func CompactToBig(compact uint32) *big.Int

CompactToBig restituisce il target in formato * big.Int

func DBexists

func DBexists(path string) bool

DBexists restituisce true se il database esiste

func GetNextWorkRequired

func GetNextWorkRequired() uint32

GetNextWorkRequired utilizza nBits dell'ultimo blocco per computare nBits del prossimo blocco

func Handle

func Handle(err error)

Handle error hanlder

func ToHex

func ToHex(num int64) []byte

ToHex dato un int 64 lo scrive in formato BigEndian

Types

type Block

type Block struct {
	BlockHeader // Testata
	//
	Hash         []byte         // 32 bytes
	Transactions []*Transaction // Transazioni
	Height       int
}

Block Blocco della catena

func CreateNewBlock

func CreateNewBlock(txs []*Transaction, prevHash []byte, height int) *Block

CreateNewBlock creates a new block in questa parte cambia la firma della funzione in quanto vengono inserite le transazioni e non dati arbitrari

func Deserialize

func Deserialize(data []byte) *Block

Deserialize deserialize a block

func Genesis

func Genesis(coinbase *Transaction) *Block

Genesis the first block of the chain Anche il blocco di genesis cambia introducendo la transazione coinbase

func (*Block) HashTransactions

func (block *Block) HashTransactions() []byte

HashTransactions crea l'hash delle transazioni

func (*Block) Serialize

func (block *Block) Serialize() []byte

Serialize serialize a block

type BlockChainIterator

type BlockChainIterator struct {
	CurrentHash []byte
	Database    *badger.DB
}

func (*BlockChainIterator) Next

func (iter *BlockChainIterator) Next() *Block

type BlockHeader

type BlockHeader struct {
	// Testata (header)
	Version        int
	HashPrevBlock  []byte
	HashMerkleRoot []byte
	Time           int64
	Bits           uint32
	Nonce          int
}

BlockHeader testata del blocco

TESTATA (BLOCK HEADER)

Version: 4 bytes Versione del blocco HashPrevBlock: 32 bytes Hash del blocco che viene referenziato da questo blocco (precedente) HashMerkleRoot 32 bytes Hash di tutte le transazioni del blocco ottenuto tramite l'albero di Merkle Time: 4 bytes A timestamp recording when this block was created (Will overflow in 2106[2]) Bits: 4 bytes Valore della difficoltà (TARGET) calcolata per questo blocco Nonce: 4 bytes Il Nonce usato per generare il blocco: è utilizzato dall'algoritmo di Proof of Works per generare l'hash del blocco in conformità con il target

        ————————
        80 bytes  Totale

I peer scambiano prima la testata.

type COutPoint

type COutPoint struct {
	PrevTxID []byte
	OutIndex int
}

COutPoint una combinazione dell'hash di una transazione e dell'indice del suo VOut

type CTxIn

type CTxIn struct {
	PubKey    []byte // dovrebbe essere ScriptSig <sig><pubKey>, qui è la chiave pubblica PubKey del soggetto emittente
	Signature []byte
	Prevout   COutPoint
}

CTxIn ingresso della transazione

  • COutPoint: referenzia un CTxOut precedente tramite la coppia:

  • PrevTxID: referenzia una Transazione precedente (escluso CTxIn Coinbase)

  • OutIndex: indice della transazione di uscita TxOutput della transazione referenziata

  • PubKey: Chiave Pubblica del soggetto che emette la transazione (deve combaciare con UTXO referenziato) in realta questa è una semplificazione; in Bitcoin questo campo è sostituito da ScriptSig

  • Signature: la firma dell'HASH della transazione fatta a mezzo della chiave privata di colui che trasferisce L'algoritmo usato in questo codice per firmare è ECDSA [Elliptic Curve Digital Signature Algorithm](https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm)

    Note A partire da SegWit (segregated witness) la firma di una transazione SegWit non fa più parte della transazione ma viene collegata in una "catena separata". Questa modifica è stata introdotta con due scopi:

  • problema della malleabilità di una transazione

  • scalare il protocollo inserendo più transazioni un blocco

func (*CTxIn) UsesKey

func (in *CTxIn) UsesKey(pubKeyHash []byte) bool

UsesKey verifies the PubKey (Hash) of the TXInput transaction

type CTxOut

type CTxOut struct {
	Value      int    // ammontare da trasferire. TODO: Satoshi
	PubKeyHash []byte // dovrebbe essere scriptPubKey, qui è la PubKeyHash (RIPEMD-160) del destinatario

}

CTxOut uscita della transazione

  • Value: il valore del TXO
  • PubKeyHash: l'hash della Chiave Pubblica del soggetto destinatario in realta questa è una semplificazione; in Bitcoin questo campo è sostituito da ScriptPubKey

func NewTXOutput

func NewTXOutput(value int, address string) *CTxOut

NewTXOutput returns a new TXO of a given amount and locked by the owner

func (*CTxOut) IsLockedWithKey

func (out *CTxOut) IsLockedWithKey(pubKeyHash []byte) bool

IsLockedWithKey given the PubKey hash checks the TXO ownership

func (*CTxOut) Lock

func (out *CTxOut) Lock(address []byte)

Lock blocca il TxOutput con la PubKey (HASH RIPEMD-160, 20 byte) del destinatario questo metodo di TxOutput, dato un indirizzo Bitcoin, ne ricava il PubKeyHash notare che dalla decodifica dell'indirizzo Base58 sono rimossi la versione e il checksum (1° e ultimi 4 byte della decodifica)

type Chain

type Chain struct {
	LastHash []byte
	Database *badger.DB
}

Chain the blockchain ledger

func ContinueBlockChain

func ContinueBlockChain(nodeID string) *Chain

ContinueBlockChain restituisce la Block Chain

func InitBlockChain

func InitBlockChain(address, nodeID string) *Chain

InitBlockChain init the BlockChain with the Genesis block

func (*Chain) AddBlock

func (chain *Chain) AddBlock(block *Block)

AddBlock add a block to the BlockChain structure

func (*Chain) FindTransaction

func (chain *Chain) FindTransaction(ID []byte) (Transaction, error)

FindTransaction trova una transazione attraverso l'ID (hash)

func (*Chain) FindUTXO

func (chain *Chain) FindUTXO() map[string]TxOutputs

FindUTXO restituisce UTXO iterando la catena

func (*Chain) GetBestHeight

func (chain *Chain) GetBestHeight() int

GetBestHeight restituisce l'altezza

func (*Chain) GetBlock

func (chain *Chain) GetBlock(blockHash []byte) (Block, error)

GetBlock dato l'hash restituisce un blocco o un errore

func (*Chain) GetBlockHashes

func (chain *Chain) GetBlockHashes() [][]byte

GetBlockHashes restituisce gli hash

func (*Chain) Iterator

func (chain *Chain) Iterator() *BlockChainIterator

func (*Chain) MineBlock

func (chain *Chain) MineBlock(transactions []*Transaction) *Block

MineBlock crea nuovi blocchi

func (*Chain) SignTransaction

func (chain *Chain) SignTransaction(tx *Transaction, privKey ecdsa.PrivateKey)

SignTransaction firma la transazione

func (*Chain) VerifyTransaction

func (chain *Chain) VerifyTransaction(tx *Transaction) bool

VerifyTransaction verifica la transazione tx costruisce una mappa ( k, v ) = (TxI, Transaction) e la sottopone a verifica

type Iterator

type Iterator struct {
	CurrentHash []byte
	Database    *badger.DB
}

Iterator the iterator struct it keeps a reference to the DB and the last hash

type MerkleNode

type MerkleNode struct {
	Left  *MerkleNode
	Right *MerkleNode
	Data  []byte
}

func NewMerkleNode

func NewMerkleNode(left, right *MerkleNode, data []byte) *MerkleNode

type MerkleTree

type MerkleTree struct {
	RootNode *MerkleNode
}

func NewMerkleTree

func NewMerkleTree(data [][]byte) *MerkleTree

type ProofOfWork

type ProofOfWork struct {
	Block  *Block
	Target *big.Int // TODO: implementare Compat, chainParams e ricavare la difficoltà dai blocchi
}

ProofOfWork struttura che contiene il blocco e il target

func NewProof

func NewProof(block *Block) *ProofOfWork

NewProof ritorna una struttura pow completa di target

func (*ProofOfWork) CheckProofOfWork

func (pow *ProofOfWork) CheckProofOfWork() bool

CheckProofOfWork valida il nonce

func (*ProofOfWork) InitData

func (pow *ProofOfWork) InitData(nonce int) []byte

InitData metodo di ProofOfWork che ritorna i dati da sottoporre ad hash

func (*ProofOfWork) Run

func (pow *ProofOfWork) Run() (int, []byte)

Run metodo di ProofOfWork che incrementa il nonce e calcola l'hash fino a trovare il target

type Transaction

type Transaction struct {
	ID []byte
	// la lettera V è utilizzata in analogia a Bitcoin dove questo membro è un vector
	Vin  []CTxIn
	Vout []CTxOut
}

Transaction una transazione è composta da due aggregati: il riferimento a transazioni precedenti le transazioni in ingresso (TxInput) e le transazioni in uscita (TxOutput)

TODO: esistono transazioni orfane

func CoinbaseTx

func CoinbaseTx(to, data string) *Transaction

CoinbaseTx la transazione Coinbase è la prima transazione della catena. Ne viene aggiunta una ad ogni blocco e rappresenta l'incentivo destinato a chi ha formato il blocco è una transazione speciale perché non necessità di referenziare nessuna transazione precedente.

func DeserializeTransaction

func DeserializeTransaction(data []byte) Transaction

DeserializeTransaction de-serializza la transazione

func NewTransaction

func NewTransaction(w *wallet.Wallet, to string, amount int, UTXO *UTXOSet) *Transaction

NewTransaction genera una nuova transazione

- from: = indirizzo sorgente - to: indirizzo destinatario - amount = valore - chain: riferimento alla block chain

* Recupera il wallet e preleva l'indirizzo del soggetto emittente * solo il soggetto emittente detiene la chiave privata all'interno del wallet * crea il pubKeyHash a partire dalla chiave pubblica [REV KEY CHECKSUM] * cerca gli UTXO necessari per spendere il valore amout attraverso la pubKeyHash e ne computa il valore totale (se inferiore al necessario termina) * itera gli UTXO. Gli UTXO sono raggruppati per transazione, dunque spendableOutputs è uma mappa chiave valore { "TXID" : [ TXO ] } * genera gli input della transazione * genera gli output della transazione ponendo il PubKeyHash del soggetto destinatario * firma la transazione

func (*Transaction) Hash

func (tx *Transaction) Hash() []byte

Hash hash della transazione serializza la transazione e ne restituisce l'hash SHA-256

func (*Transaction) IsCoinbase

func (tx *Transaction) IsCoinbase() bool

IsCoinbase determina se una transazione è la transazione Coinbase

func (Transaction) Serialize

func (tx Transaction) Serialize() []byte

Serialize serializza la transazione

func (*Transaction) Sign

func (tx *Transaction) Sign(privKey ecdsa.PrivateKey, prevTXs map[string]Transaction)

Sign firma la transazione

func (Transaction) String

func (tx Transaction) String() string

String restituisce una rappresentazione testuale della transazione

func (*Transaction) TrimmedCopy

func (tx *Transaction) TrimmedCopy() Transaction

TrimmedCopy versione semplificata della transazione Serve per firmare e verificare la transazione infatti la firma e la verifica avvengono sulla serializzazione della transazione semplificata

func (*Transaction) Verify

func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool

Verify verifica la transazione

type TxOutputs

type TxOutputs struct {
	Outputs []CTxOut
}

TxOutputs una collezione di TxOutput

func DeserializeOutputs

func DeserializeOutputs(data []byte) TxOutputs

DeserializeOutputs deserializza TxOutputs

func (TxOutputs) Serialize

func (outs TxOutputs) Serialize() []byte

Serialize serializza TxOutputs

type UTXOSet

type UTXOSet struct {
	Blockchain *Chain
}

UTXOSet a struct that manages UTXO

func (UTXOSet) CountTransactions

func (u UTXOSet) CountTransactions() int

CountTransactions conta le transazione nell UTXO Set

func (*UTXOSet) DeleteByPrefix

func (u *UTXOSet) DeleteByPrefix(prefix []byte)

DeleteByPrefix cancella

func (UTXOSet) FindSpendableOutputs

func (u UTXOSet) FindSpendableOutputs(pubKeyHash []byte, amount int) (int, map[string][]int)

FindSpendableOutputs restituisce una mappa di UTXO

func (UTXOSet) FindUnspentTransactions

func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []CTxOut

FindUTXO cerca e restituisce un UTXO referenziato attraverso pubKeyHash

func (UTXOSet) Reindex

func (u UTXOSet) Reindex()

Reindex indicizza l'UTXO Set

func (*UTXOSet) Update

func (u *UTXOSet) Update(block *Block)

Update aggiorna l'UTXO Set

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL