├── LICENSE ├── README.md ├── blockchain ├── block.go ├── blockchain.go ├── merkle.go ├── proof.go ├── transaction.go ├── tx.go └── utxo.go ├── cli └── cli.go ├── database └── database.go ├── main.go ├── network ├── models.go ├── network.go └── util.go └── wallet ├── utils.go ├── wallet.go └── wallets.go /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 İbrahim Süren 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Blockchain in Go 2 | [![Go Report Card](https://goreportcard.com/badge/github.com/ibrahimsn98/blockchain-in-go)](https://goreportcard.com/report/github.com/ibrahimsn98/blockchain-in-go) 3 | [![GitHub version](https://badge.fury.io/gh/ibrahimsn98%2Fblockchain-in-go.svg)](https://badge.fury.io/gh/ibrahimsn98%2Fblockchain-in-go) 4 | 5 | A basic blockchain implementation in Golang 6 | 7 | ## Usage 8 | Get the balance for an address 9 | ``` 10 | $ go run main.go getbalance -address ADDRESS 11 | ``` 12 | 13 | Create a blockchain and send genesis reward to address 14 | ``` 15 | $ go run main.go createblockchain -address ADDRESS 16 | ``` 17 | 18 | Print the blocks in the chain 19 | ``` 20 | $ go run main.go printchain 21 | ``` 22 | 23 | Send amount of coins 24 | ``` 25 | $ go run main.go send -from FROM -to TO -amount AMOUNT 26 | ``` 27 | 28 | Create a new Wallet 29 | ``` 30 | $ go run main.go createwallet 31 | ``` 32 | 33 | List the addresses in wallet file 34 | ``` 35 | $ go run main.go listaddresses 36 | ``` 37 | 38 | Rebuild the UTXO set 39 | ``` 40 | $ go run main.go reindexutxo 41 | ``` 42 | 43 | Start a node with ID specified in NODE_ID env. var. -miner enables mining 44 | ``` 45 | $ go run main.go startnode -miner ADDRESS 46 | ``` 47 | 48 | ## Wiki 49 | - [Basic Terminology](https://github.com/ibrahimsn98/blockchain-in-go/wiki/Basic-Terminology) 50 | - [How is the wallet address created?](https://github.com/ibrahimsn98/blockchain-in-go/wiki/How-is-the-wallet-address-created%3F) 51 | 52 | 53 | ## Requirements 54 | - github.com/dgraph-io/badger 55 | - github.com/mr-tron/base58 56 | - golang.org/x/crypto 57 | - gopkg.in/vrecan/death.v3 58 | 59 | 60 | ### Video Tutorials 61 | [Tensor Programming](https://www.youtube.com/channel/UCYqCZOwHbnPwyjawKfE21wg) 62 | 63 | ## License 64 | [MIT](https://choosealicense.com/licenses/mit/) 65 | 66 | -------------------------------------------------------------------------------- /blockchain/block.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | "log" 7 | "time" 8 | ) 9 | 10 | type Block struct { 11 | Timestamp int64 12 | Hash []byte 13 | Transactions []*Transaction 14 | PrevHash []byte 15 | Nonce int 16 | Height int 17 | } 18 | 19 | func (b *Block) HashTransactions() []byte { 20 | var txHashes [][]byte 21 | 22 | for _, tx := range b.Transactions { 23 | txHashes = append(txHashes, tx.Serialize()) 24 | } 25 | tree := NewMerkleTree(txHashes) 26 | 27 | return tree.RootNode.Data 28 | } 29 | 30 | func CreateBlock(txs []*Transaction, prevHash []byte, height int) *Block { 31 | block := &Block{time.Now().Unix(), []byte{}, txs, prevHash, 0, height} 32 | pow := NewProof(block) 33 | nonce, hash := pow.Run() 34 | 35 | block.Hash = hash[:] 36 | block.Nonce = nonce 37 | 38 | return block 39 | } 40 | 41 | func Genesis(coinbase *Transaction) *Block { 42 | return CreateBlock([]*Transaction{coinbase}, []byte{}, 0) 43 | } 44 | 45 | func (b *Block) Serialize() []byte { 46 | var res bytes.Buffer 47 | encoder := gob.NewEncoder(&res) 48 | 49 | err := encoder.Encode(b) 50 | 51 | Handle(err) 52 | 53 | return res.Bytes() 54 | } 55 | 56 | func Deserialize(data []byte) *Block { 57 | var block Block 58 | 59 | decoder := gob.NewDecoder(bytes.NewReader(data)) 60 | 61 | err := decoder.Decode(&block) 62 | 63 | Handle(err) 64 | 65 | return &block 66 | } 67 | 68 | func Handle(err error) { 69 | if err != nil { 70 | log.Panic(err) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /blockchain/blockchain.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "blockchain/main/database" 5 | "bytes" 6 | "crypto/ecdsa" 7 | "encoding/hex" 8 | "errors" 9 | "fmt" 10 | "log" 11 | "os" 12 | "runtime" 13 | ) 14 | 15 | const ( 16 | dbPath = "/tmp/blocks_%s" 17 | genesisData = "First Transaction from Genesis" 18 | ) 19 | 20 | type BlockChain struct { 21 | LastHash []byte 22 | Database *database.Database 23 | } 24 | 25 | type ChainIterator struct { 26 | CurrentHash []byte 27 | Database *database.Database 28 | } 29 | 30 | func DBExists(path string) bool { 31 | if _, err := os.Stat(path + "/MANIFEST"); os.IsNotExist(err) { 32 | return false 33 | } 34 | 35 | return true 36 | } 37 | 38 | func InitBlockChain(address, nodeId string) *BlockChain { 39 | path := fmt.Sprintf(dbPath, nodeId) 40 | 41 | if DBExists(path) { 42 | fmt.Println("Blockchain already exists.") 43 | runtime.Goexit() 44 | } 45 | 46 | // Get database instance 47 | db, err := database.GetDatabase(path) 48 | Handle(err) 49 | 50 | // Create coinbase transaction 51 | cbtx := CoinbaseTx(address, genesisData) 52 | 53 | // Create genesis block 54 | genesis := Genesis(cbtx) 55 | fmt.Println("Genesis created") 56 | 57 | // Store genesis block data 58 | err = db.Update(genesis.Hash, genesis.Serialize()) 59 | Handle(err) 60 | 61 | // Set last hash as genesis block hash 62 | err = db.Update([]byte("lh"), genesis.Hash) 63 | Handle(err) 64 | 65 | // Return chain that has only genesis block 66 | blockchain := BlockChain{genesis.Hash, db} 67 | return &blockchain 68 | } 69 | 70 | func ContinueBlockChain(nodeId string) *BlockChain { 71 | path := fmt.Sprintf(dbPath, nodeId) 72 | 73 | if DBExists(path) == false { 74 | fmt.Println("No existing blockchain found, create one!") 75 | runtime.Goexit() 76 | } 77 | 78 | db, err := database.GetDatabase(path) 79 | Handle(err) 80 | 81 | // Get last block hash 82 | lastHash, err := db.Read([]byte("lh")) 83 | Handle(err) 84 | 85 | chain := BlockChain{lastHash, db} 86 | return &chain 87 | } 88 | 89 | func (chain *BlockChain) MineBlock(transactions []*Transaction) *Block { 90 | for _, tx := range transactions { 91 | if chain.VerifyTransaction(tx) != true { 92 | log.Panic("Invalid Transaction") 93 | } 94 | } 95 | 96 | // Get last block hash 97 | lastHash, err := chain.Database.Read([]byte("lh")) 98 | Handle(err) 99 | 100 | // Get serialized last block data 101 | lastBlockBytes, err := chain.Database.Read(lastHash) 102 | Handle(err) 103 | 104 | // Deserialize byte data to block 105 | lastBlock := *Deserialize(lastBlockBytes) 106 | 107 | // Create new block 108 | newBlock := CreateBlock(transactions, lastHash, lastBlock.Height+1) 109 | 110 | // Store new block 111 | err = chain.Database.Update(newBlock.Hash, newBlock.Serialize()) 112 | Handle(err) 113 | 114 | // Update last block hash 115 | err = chain.Database.Update([]byte("lh"), newBlock.Hash) 116 | Handle(err) 117 | 118 | chain.LastHash = newBlock.Hash 119 | 120 | return newBlock 121 | } 122 | 123 | func (chain *BlockChain) AddBlock(block *Block) { 124 | 125 | // If the chain already has this block, cancel the process 126 | _, err := chain.Database.Read(block.Hash) 127 | if err == nil { 128 | return 129 | } 130 | 131 | // Store new block 132 | err = chain.Database.Update(block.Hash, block.Serialize()) 133 | Handle(err) 134 | 135 | // Get last block hash 136 | lastHash, err := chain.Database.Read([]byte("lh")) 137 | Handle(err) 138 | 139 | // Get serialized last block data 140 | lastBlockData, err := chain.Database.Read(lastHash) 141 | Handle(err) 142 | 143 | // Deserialize byte data to block 144 | lastBlock := Deserialize(lastBlockData) 145 | 146 | // If block height is bigger than last block height, set it as the last block 147 | if block.Height > lastBlock.Height { 148 | err := chain.Database.Update([]byte("lh"), block.Hash) 149 | Handle(err) 150 | 151 | chain.LastHash = block.Hash 152 | } 153 | } 154 | 155 | func (chain *BlockChain) GetBlockHashes() [][]byte { 156 | var blocks [][]byte 157 | 158 | iter := chain.Iterator() 159 | 160 | for { 161 | block := iter.Next() 162 | blocks = append(blocks, block.Hash) 163 | 164 | // Iterate until the first block 165 | if len(block.PrevHash) == 0 { 166 | break 167 | } 168 | } 169 | 170 | return blocks 171 | } 172 | 173 | func (chain *BlockChain) GetBlock(blockHash []byte) (Block, error) { 174 | blockData, err := chain.Database.Read(blockHash) 175 | 176 | if err != nil { 177 | log.Panic("block is not found") 178 | } 179 | 180 | return *Deserialize(blockData), err 181 | } 182 | 183 | func (chain *BlockChain) GetBestHeight() int { 184 | lastHash, err := chain.Database.Read([]byte("lh")) 185 | Handle(err) 186 | 187 | lastBlockData, err := chain.Database.Read(lastHash) 188 | Handle(err) 189 | 190 | lastBlock := *Deserialize(lastBlockData) 191 | 192 | return lastBlock.Height 193 | } 194 | 195 | func (chain *BlockChain) Iterator() *ChainIterator { 196 | return &ChainIterator{chain.LastHash, chain.Database} 197 | } 198 | 199 | func (iter *ChainIterator) Next() *Block { 200 | currentBlockData, err := iter.Database.Read(iter.CurrentHash) 201 | Handle(err) 202 | 203 | block := Deserialize(currentBlockData) 204 | iter.CurrentHash = block.PrevHash 205 | 206 | return block 207 | } 208 | 209 | // Finds unspent transaction outputs 210 | // Unspent means that these outputs were not referenced in any inputs 211 | func (chain *BlockChain) FindUTXO() map[string]TxOutputs { 212 | UTXO := make(map[string]TxOutputs) 213 | spentTXOs := make(map[string][]int) 214 | 215 | iter := chain.Iterator() 216 | 217 | for { 218 | block := iter.Next() 219 | 220 | // Iterate transactions 221 | for _, tx := range block.Transactions { 222 | txID := hex.EncodeToString(tx.ID) 223 | 224 | Outputs: 225 | // Iterate transaction outputs 226 | for outIdx, out := range tx.Outputs { 227 | if spentTXOs[txID] != nil { 228 | for _, spentOut := range spentTXOs[txID] { 229 | if spentOut == outIdx { 230 | continue Outputs 231 | } 232 | } 233 | } 234 | 235 | outs := UTXO[txID] 236 | outs.Outputs = append(outs.Outputs, out) 237 | UTXO[txID] = outs 238 | } 239 | 240 | if tx.IsCoinbase() == false { 241 | for _, in := range tx.Inputs { 242 | inTxID := hex.EncodeToString(in.ID) 243 | spentTXOs[inTxID] = append(spentTXOs[inTxID], in.Out) 244 | } 245 | } 246 | } 247 | 248 | if len(block.PrevHash) == 0 { 249 | break 250 | } 251 | } 252 | return UTXO 253 | } 254 | 255 | func (chain *BlockChain) FindUnspentTransactions(pubKeyHash []byte) []Transaction { 256 | var unspentTxs []Transaction 257 | 258 | spentTXOs := make(map[string][]int) 259 | 260 | iter := chain.Iterator() 261 | 262 | for { 263 | block := iter.Next() 264 | 265 | // Iterate transactions 266 | for _, tx := range block.Transactions { 267 | txID := hex.EncodeToString(tx.ID) 268 | 269 | Outputs: 270 | // Iterate transaction outputs 271 | for outIdx, out := range tx.Outputs { 272 | if spentTXOs[txID] != nil { 273 | for _, spentOut := range spentTXOs[txID] { 274 | if spentOut == outIdx { 275 | continue Outputs 276 | } 277 | } 278 | } 279 | 280 | if out.IsLockedWithKey(pubKeyHash) { 281 | unspentTxs = append(unspentTxs, *tx) 282 | } 283 | } 284 | 285 | if tx.IsCoinbase() == false { 286 | for _, in := range tx.Inputs { 287 | if in.UsesKey(pubKeyHash) { 288 | inTxID := hex.EncodeToString(in.ID) 289 | spentTXOs[inTxID] = append(spentTXOs[inTxID], in.Out) 290 | } 291 | } 292 | } 293 | } 294 | 295 | if len(block.PrevHash) == 0 { 296 | break 297 | } 298 | } 299 | return unspentTxs 300 | } 301 | 302 | func (chain *BlockChain) FindSpendableOutputs(pubKeyHash []byte, amount int) (int, map[string][]int) { 303 | unspentOuts := make(map[string][]int) 304 | unspentTxs := chain.FindUnspentTransactions(pubKeyHash) 305 | accumulated := 0 306 | 307 | Work: 308 | for _, tx := range unspentTxs { 309 | txID := hex.EncodeToString(tx.ID) 310 | 311 | for outIdx, out := range tx.Outputs { 312 | if out.IsLockedWithKey(pubKeyHash) && accumulated < amount { 313 | accumulated += out.Value 314 | unspentOuts[txID] = append(unspentOuts[txID], outIdx) 315 | 316 | if accumulated >= amount { 317 | break Work 318 | } 319 | } 320 | } 321 | } 322 | 323 | return accumulated, unspentOuts 324 | } 325 | 326 | func (chain *BlockChain) FindTransaction(ID []byte) (Transaction, error) { 327 | iter := chain.Iterator() 328 | 329 | for { 330 | block := iter.Next() 331 | 332 | for _, tx := range block.Transactions { 333 | if bytes.Compare(tx.ID, ID) == 0 { 334 | return *tx, nil 335 | } 336 | } 337 | 338 | if len(block.PrevHash) == 0 { 339 | break 340 | } 341 | } 342 | 343 | return Transaction{}, errors.New("transaction does not exist") 344 | } 345 | 346 | func (chain *BlockChain) SignTransaction(tx *Transaction, privateKey ecdsa.PrivateKey) { 347 | prevTXs := make(map[string]Transaction) 348 | 349 | // Iterate previous transactions 350 | for _, in := range tx.Inputs { 351 | prevTX, err := chain.FindTransaction(in.ID) 352 | Handle(err) 353 | prevTXs[hex.EncodeToString(prevTX.ID)] = prevTX 354 | } 355 | 356 | tx.Sign(privateKey, prevTXs) 357 | } 358 | 359 | func (chain *BlockChain) VerifyTransaction(tx *Transaction) bool { 360 | 361 | if tx.IsCoinbase() { 362 | return true 363 | } 364 | 365 | prevTXs := make(map[string]Transaction) 366 | 367 | for _, in := range tx.Inputs { 368 | fmt.Println("TX: " + hex.EncodeToString(tx.ID) + "\nInput Prev: " + hex.EncodeToString(in.ID)) 369 | 370 | prevTX, err := chain.FindTransaction(in.ID) 371 | Handle(err) 372 | 373 | fmt.Println("Tx in DB: " + hex.EncodeToString(prevTX.ID)) 374 | 375 | prevTXs[hex.EncodeToString(prevTX.ID)] = prevTX 376 | } 377 | 378 | return tx.Verify(prevTXs) 379 | } 380 | -------------------------------------------------------------------------------- /blockchain/merkle.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "crypto/sha256" 5 | "log" 6 | ) 7 | 8 | type MerkleTree struct { 9 | RootNode *MerkleNode 10 | } 11 | 12 | type MerkleNode struct { 13 | Left *MerkleNode 14 | Right *MerkleNode 15 | Data []byte 16 | } 17 | 18 | func NewMerkleNode(left, right *MerkleNode, data []byte) *MerkleNode { 19 | node := MerkleNode{} 20 | 21 | if left == nil && right == nil { 22 | hash := sha256.Sum256(data) 23 | node.Data = hash[:] 24 | } else { 25 | prevHashes := append(left.Data, right.Data...) 26 | hash := sha256.Sum256(prevHashes) 27 | node.Data = hash[:] 28 | } 29 | 30 | node.Left = left 31 | node.Right = right 32 | 33 | return &node 34 | } 35 | 36 | func NewMerkleTree(data [][]byte) *MerkleTree { 37 | var nodes []MerkleNode 38 | 39 | for _, dat := range data { 40 | node := NewMerkleNode(nil, nil, dat) 41 | nodes = append(nodes, *node) 42 | } 43 | 44 | if len(nodes) == 0 { 45 | log.Panic("No merkel nodes") 46 | } 47 | 48 | for len(nodes) > 1 { 49 | if len(nodes)%2 != 0 { 50 | nodes = append(nodes, nodes[len(nodes)-1]) 51 | } 52 | 53 | var level []MerkleNode 54 | for i := 0; i < len(nodes); i += 2 { 55 | node := NewMerkleNode(&nodes[i], &nodes[i+1], nil) 56 | level = append(level, *node) 57 | } 58 | 59 | nodes = level 60 | } 61 | 62 | tree := MerkleTree{&nodes[0]} 63 | 64 | return &tree 65 | } 66 | -------------------------------------------------------------------------------- /blockchain/proof.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha256" 6 | "encoding/binary" 7 | "fmt" 8 | "log" 9 | "math" 10 | "math/big" 11 | ) 12 | 13 | // PoW difficulty 14 | const Difficulty = 12 15 | 16 | // Represents proof of work 17 | type ProofOfWork struct { 18 | Block *Block 19 | Target *big.Int 20 | } 21 | 22 | // Create new PoW 23 | func NewProof(b *Block) *ProofOfWork { 24 | target := big.NewInt(1) 25 | target.Lsh(target, uint(256-Difficulty)) 26 | 27 | pow := &ProofOfWork{b, target} 28 | 29 | return pow 30 | } 31 | 32 | func (pow *ProofOfWork) InitData(nonce int) []byte { 33 | data := bytes.Join( 34 | [][]byte{ 35 | pow.Block.PrevHash, 36 | pow.Block.HashTransactions(), 37 | ToHex(int64(nonce)), 38 | ToHex(int64(Difficulty)), 39 | }, 40 | []byte{}, 41 | ) 42 | 43 | return data 44 | } 45 | 46 | func (pow *ProofOfWork) Run() (int, []byte) { 47 | var intHash big.Int 48 | var hash [32]byte 49 | 50 | nonce := 0 51 | 52 | for nonce < math.MaxInt64 { 53 | data := pow.InitData(nonce) 54 | hash = sha256.Sum256(data) 55 | 56 | fmt.Printf("\r%x", hash) 57 | intHash.SetBytes(hash[:]) 58 | 59 | if intHash.Cmp(pow.Target) == -1 { 60 | break 61 | } else { 62 | nonce++ 63 | } 64 | 65 | } 66 | 67 | fmt.Println() 68 | 69 | return nonce, hash[:] 70 | } 71 | 72 | func (pow *ProofOfWork) Validate() bool { 73 | var intHash big.Int 74 | 75 | data := pow.InitData(pow.Block.Nonce) 76 | 77 | hash := sha256.Sum256(data) 78 | intHash.SetBytes(hash[:]) 79 | 80 | return intHash.Cmp(pow.Target) == -1 81 | } 82 | 83 | func ToHex(num int64) []byte { 84 | buff := new(bytes.Buffer) 85 | err := binary.Write(buff, binary.BigEndian, num) 86 | if err != nil { 87 | log.Panic(err) 88 | 89 | } 90 | 91 | return buff.Bytes() 92 | } 93 | -------------------------------------------------------------------------------- /blockchain/transaction.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "blockchain/main/wallet" 5 | "bytes" 6 | "crypto/ecdsa" 7 | "crypto/elliptic" 8 | "crypto/rand" 9 | "crypto/sha256" 10 | "encoding/gob" 11 | "encoding/hex" 12 | "fmt" 13 | "io" 14 | "log" 15 | "math/big" 16 | "strings" 17 | ) 18 | 19 | type Transaction struct { 20 | ID []byte 21 | Inputs []TxInput 22 | Outputs []TxOutput 23 | } 24 | 25 | func (tx *Transaction) Hash() []byte { 26 | var hash [32]byte 27 | 28 | txCopy := *tx 29 | txCopy.ID = []byte{} 30 | 31 | salt := make([]byte, 32) 32 | _, err := io.ReadFull(rand.Reader, salt) 33 | if err != nil { 34 | fmt.Printf("ERROR: Creating salt failed: %s\n", err) 35 | } 36 | 37 | data := txCopy.Serialize() 38 | data = append(data, salt...) 39 | 40 | // Perform sha256 on serialized transaction 41 | hash = sha256.Sum256(data) 42 | 43 | return hash[:] 44 | } 45 | 46 | func (tx Transaction) Serialize() []byte { 47 | var encoded bytes.Buffer 48 | 49 | enc := gob.NewEncoder(&encoded) 50 | err := enc.Encode(tx) 51 | if err != nil { 52 | log.Panic(err) 53 | } 54 | 55 | return encoded.Bytes() 56 | } 57 | 58 | func DeserializeTransaction(data []byte) Transaction { 59 | var transaction Transaction 60 | 61 | decoder := gob.NewDecoder(bytes.NewReader(data)) 62 | err := decoder.Decode(&transaction) 63 | Handle(err) 64 | 65 | return transaction 66 | } 67 | 68 | func CoinbaseTx(to, data string) *Transaction { 69 | if data == "" { 70 | randData := make([]byte, 24) 71 | _, err := rand.Read(randData) 72 | Handle(err) 73 | data = fmt.Sprintf("%x", randData) 74 | } 75 | 76 | txin := TxInput{[]byte{}, -1, nil, []byte(data)} 77 | txout := NewTXOutput(20, to) 78 | 79 | tx := Transaction{nil, []TxInput{txin}, []TxOutput{*txout}} 80 | tx.ID = tx.Hash() 81 | 82 | return &tx 83 | } 84 | 85 | func NewTransaction(w *wallet.Wallet, to string, amount int, UTXO *UTXOSet) *Transaction { 86 | var inputs []TxInput 87 | var outputs []TxOutput 88 | 89 | pubKeyHash := wallet.PublicKeyHash(w.PublicKey) 90 | acc, validOutputs := UTXO.FindSpendableOutputs(pubKeyHash, amount) 91 | 92 | if acc < amount { 93 | log.Panic("Error: not enough funds") 94 | } 95 | 96 | for encodedTxID, outs := range validOutputs { 97 | txID, err := hex.DecodeString(encodedTxID) 98 | Handle(err) 99 | 100 | for _, out := range outs { 101 | input := TxInput{txID, out, nil, w.PublicKey} 102 | inputs = append(inputs, input) 103 | } 104 | } 105 | 106 | from := fmt.Sprintf("%s", w.Address()) 107 | 108 | outputs = append(outputs, *NewTXOutput(amount, to)) 109 | 110 | if acc > amount { 111 | outputs = append(outputs, *NewTXOutput(acc-amount, from)) 112 | } 113 | 114 | tx := Transaction{nil, inputs, outputs} 115 | tx.ID = tx.Hash() 116 | UTXO.BlockChain.SignTransaction(&tx, w.PrivateKey) 117 | 118 | return &tx 119 | } 120 | 121 | func (tx *Transaction) IsCoinbase() bool { 122 | return len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1 123 | } 124 | 125 | func (tx *Transaction) Sign(privateKey ecdsa.PrivateKey, prevTXs map[string]Transaction) { 126 | if tx.IsCoinbase() { 127 | return 128 | } 129 | 130 | for _, in := range tx.Inputs { 131 | if prevTXs[hex.EncodeToString(in.ID)].ID == nil { 132 | log.Panic("ERROR: Previous transaction is not correct") 133 | } 134 | } 135 | 136 | txCopy := tx.TrimmedCopy() 137 | 138 | for inId, in := range txCopy.Inputs { 139 | prevTX := prevTXs[hex.EncodeToString(in.ID)] 140 | txCopy.Inputs[inId].Signature = nil 141 | txCopy.Inputs[inId].PubKey = prevTX.Outputs[in.Out].PubKeyHash 142 | 143 | dataToSign := fmt.Sprintf("%x\n", txCopy) 144 | 145 | r, s, err := ecdsa.Sign(rand.Reader, &privateKey, []byte(dataToSign)) 146 | Handle(err) 147 | signature := append(r.Bytes(), s.Bytes()...) 148 | 149 | tx.Inputs[inId].Signature = signature 150 | txCopy.Inputs[inId].PubKey = nil 151 | } 152 | } 153 | 154 | func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool { 155 | if tx.IsCoinbase() { 156 | return true 157 | } 158 | 159 | for _, in := range tx.Inputs { 160 | if prevTXs[hex.EncodeToString(in.ID)].ID == nil { 161 | log.Panic("Previous transaction not correct") 162 | } 163 | } 164 | 165 | txCopy := tx.TrimmedCopy() 166 | curve := elliptic.P256() 167 | 168 | for inId, in := range tx.Inputs { 169 | prevTx := prevTXs[hex.EncodeToString(in.ID)] 170 | txCopy.Inputs[inId].Signature = nil 171 | txCopy.Inputs[inId].PubKey = prevTx.Outputs[in.Out].PubKeyHash 172 | 173 | r := big.Int{} 174 | s := big.Int{} 175 | 176 | sigLen := len(in.Signature) 177 | r.SetBytes(in.Signature[:(sigLen / 2)]) 178 | s.SetBytes(in.Signature[(sigLen / 2):]) 179 | 180 | x := big.Int{} 181 | y := big.Int{} 182 | keyLen := len(in.PubKey) 183 | x.SetBytes(in.PubKey[:(keyLen / 2)]) 184 | y.SetBytes(in.PubKey[(keyLen / 2):]) 185 | 186 | dataToVerify := fmt.Sprintf("%x\n", txCopy) 187 | 188 | rawPubKey := ecdsa.PublicKey{Curve: curve, X: &x, Y: &y} 189 | if ecdsa.Verify(&rawPubKey, []byte(dataToVerify), &r, &s) == false { 190 | return false 191 | } 192 | txCopy.Inputs[inId].PubKey = nil 193 | } 194 | 195 | return true 196 | } 197 | 198 | func (tx *Transaction) TrimmedCopy() Transaction { 199 | var inputs []TxInput 200 | var outputs []TxOutput 201 | 202 | for _, in := range tx.Inputs { 203 | inputs = append(inputs, TxInput{in.ID, in.Out, nil, nil}) 204 | } 205 | 206 | for _, out := range tx.Outputs { 207 | outputs = append(outputs, TxOutput{out.Value, out.PubKeyHash}) 208 | } 209 | 210 | txCopy := Transaction{tx.ID, inputs, outputs} 211 | 212 | return txCopy 213 | } 214 | 215 | func (tx Transaction) String() string { 216 | var lines []string 217 | 218 | lines = append(lines, fmt.Sprintf("--- Transaction %x:", tx.ID)) 219 | for i, input := range tx.Inputs { 220 | lines = append(lines, fmt.Sprintf(" Input %d:", i)) 221 | lines = append(lines, fmt.Sprintf(" TXID: %x", input.ID)) 222 | lines = append(lines, fmt.Sprintf(" Out: %d", input.Out)) 223 | lines = append(lines, fmt.Sprintf(" Signature: %x", input.Signature)) 224 | lines = append(lines, fmt.Sprintf(" PubKey: %x", input.PubKey)) 225 | } 226 | 227 | for i, output := range tx.Outputs { 228 | lines = append(lines, fmt.Sprintf(" Output %d:", i)) 229 | lines = append(lines, fmt.Sprintf(" Value: %d", output.Value)) 230 | lines = append(lines, fmt.Sprintf(" Script: %x", output.PubKeyHash)) 231 | } 232 | 233 | return strings.Join(lines, "\n") 234 | } 235 | -------------------------------------------------------------------------------- /blockchain/tx.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "blockchain/main/wallet" 5 | "bytes" 6 | "encoding/gob" 7 | ) 8 | 9 | type TxOutput struct { 10 | Value int 11 | PubKeyHash []byte 12 | } 13 | 14 | type TxOutputs struct { 15 | Outputs []TxOutput 16 | } 17 | 18 | type TxInput struct { 19 | ID []byte 20 | Out int 21 | Signature []byte 22 | PubKey []byte 23 | } 24 | 25 | func (in *TxInput) UsesKey(pubKeyHash []byte) bool { 26 | lockingHash := wallet.PublicKeyHash(in.PubKey) 27 | 28 | return bytes.Compare(lockingHash, pubKeyHash) == 0 29 | } 30 | 31 | func (out *TxOutput) Lock(address []byte) { 32 | pubKeyHash := wallet.Base58Decode(address) 33 | pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4] 34 | out.PubKeyHash = pubKeyHash 35 | } 36 | 37 | func (out *TxOutput) IsLockedWithKey(pubKeyHash []byte) bool { 38 | return bytes.Compare(out.PubKeyHash, pubKeyHash) == 0 39 | } 40 | 41 | func NewTXOutput(value int, address string) *TxOutput { 42 | txo := &TxOutput{value, nil} 43 | txo.Lock([]byte(address)) 44 | 45 | return txo 46 | } 47 | 48 | func (outs TxOutputs) Serialize() []byte { 49 | var buffer bytes.Buffer 50 | encode := gob.NewEncoder(&buffer) 51 | err := encode.Encode(outs) 52 | Handle(err) 53 | return buffer.Bytes() 54 | } 55 | 56 | func DeserializeOutputs(data []byte) TxOutputs { 57 | var outputs TxOutputs 58 | decode := gob.NewDecoder(bytes.NewReader(data)) 59 | err := decode.Decode(&outputs) 60 | Handle(err) 61 | return outputs 62 | } 63 | -------------------------------------------------------------------------------- /blockchain/utxo.go: -------------------------------------------------------------------------------- 1 | package blockchain 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "github.com/dgraph-io/badger" 7 | "log" 8 | ) 9 | 10 | var ( 11 | utxoPrefix = []byte("utxo-") 12 | ) 13 | 14 | type UTXOSet struct { 15 | BlockChain *BlockChain 16 | } 17 | 18 | func (u UTXOSet) FindSpendableOutputs(pubKeyHash []byte, amount int) (int, map[string][]int) { 19 | unspentOuts := make(map[string][]int) 20 | accumulated := 0 21 | 22 | err := u.BlockChain.Database.DB.View(func(txn *badger.Txn) error { 23 | it := txn.NewIterator(badger.DefaultIteratorOptions) 24 | defer it.Close() 25 | 26 | for it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() { 27 | item := it.Item() 28 | k := item.Key() 29 | 30 | k = bytes.TrimPrefix(k, utxoPrefix) 31 | txID := hex.EncodeToString(k) 32 | 33 | err := item.Value(func(val []byte) error { 34 | outs := DeserializeOutputs(val) 35 | 36 | for outIdx, out := range outs.Outputs { 37 | if out.IsLockedWithKey(pubKeyHash) && accumulated < amount { 38 | accumulated += out.Value 39 | unspentOuts[txID] = append(unspentOuts[txID], outIdx) 40 | } 41 | } 42 | 43 | return nil 44 | }) 45 | 46 | Handle(err) 47 | } 48 | return nil 49 | }) 50 | Handle(err) 51 | return accumulated, unspentOuts 52 | } 53 | 54 | func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput { 55 | var UTXOs []TxOutput 56 | 57 | err := u.BlockChain.Database.DB.View(func(txn *badger.Txn) error { 58 | opts := badger.DefaultIteratorOptions 59 | 60 | it := txn.NewIterator(opts) 61 | defer it.Close() 62 | 63 | for it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() { 64 | item := it.Item() 65 | var v []byte 66 | 67 | err := item.Value(func(val []byte) error { 68 | v = val 69 | return nil 70 | }) 71 | Handle(err) 72 | 73 | outs := DeserializeOutputs(v) 74 | for _, out := range outs.Outputs { 75 | if out.IsLockedWithKey(pubKeyHash) { 76 | UTXOs = append(UTXOs, out) 77 | } 78 | } 79 | 80 | } 81 | return nil 82 | }) 83 | Handle(err) 84 | 85 | return UTXOs 86 | } 87 | 88 | func (u UTXOSet) FindUTXO(pubKeyHash []byte) []TxOutput { 89 | var UTXOs []TxOutput 90 | 91 | db := u.BlockChain.Database 92 | 93 | err := db.DB.View(func(txn *badger.Txn) error { 94 | opts := badger.DefaultIteratorOptions 95 | 96 | it := txn.NewIterator(opts) 97 | defer it.Close() 98 | 99 | for it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() { 100 | item := it.Item() 101 | 102 | err := item.Value(func(val []byte) error { 103 | outs := DeserializeOutputs(val) 104 | 105 | for _, out := range outs.Outputs { 106 | if out.IsLockedWithKey(pubKeyHash) { 107 | UTXOs = append(UTXOs, out) 108 | } 109 | } 110 | 111 | return nil 112 | }) 113 | 114 | Handle(err) 115 | } 116 | 117 | return nil 118 | }) 119 | Handle(err) 120 | 121 | return UTXOs 122 | } 123 | 124 | func (u UTXOSet) CountTransactions() int { 125 | db := u.BlockChain.Database 126 | counter := 0 127 | 128 | err := db.Iterator(true, func(it *badger.Iterator) error { 129 | for it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() { 130 | counter++ 131 | } 132 | 133 | return nil 134 | }) 135 | 136 | Handle(err) 137 | 138 | return counter 139 | } 140 | 141 | func (u UTXOSet) Reindex() { 142 | db := u.BlockChain.Database 143 | 144 | u.DeleteByPrefix(utxoPrefix) 145 | 146 | UTXO := u.BlockChain.FindUTXO() 147 | 148 | err := db.DB.Update(func(txn *badger.Txn) error { 149 | for txId, outs := range UTXO { 150 | key, err := hex.DecodeString(txId) 151 | if err != nil { 152 | return err 153 | } 154 | key = append(utxoPrefix, key...) 155 | 156 | err = txn.Set(key, outs.Serialize()) 157 | Handle(err) 158 | } 159 | 160 | return nil 161 | }) 162 | Handle(err) 163 | } 164 | 165 | func (u *UTXOSet) Update(block *Block) { 166 | db := u.BlockChain.Database 167 | 168 | err := db.DB.Update(func(txn *badger.Txn) error { 169 | for _, tx := range block.Transactions { 170 | if tx.IsCoinbase() == false { 171 | for _, in := range tx.Inputs { 172 | updatedOuts := TxOutputs{} 173 | inID := append(utxoPrefix, in.ID...) 174 | item, err := txn.Get(inID) 175 | Handle(err) 176 | 177 | err = item.Value(func(val []byte) error { 178 | outs := DeserializeOutputs(val) 179 | 180 | for outIdx, out := range outs.Outputs { 181 | if outIdx != in.Out { 182 | updatedOuts.Outputs = append(updatedOuts.Outputs, out) 183 | } 184 | } 185 | 186 | if len(updatedOuts.Outputs) == 0 { 187 | if err := txn.Delete(inID); err != nil { 188 | log.Panic(err) 189 | } 190 | 191 | } else { 192 | if err := txn.Set(inID, updatedOuts.Serialize()); err != nil { 193 | log.Panic(err) 194 | } 195 | } 196 | 197 | return nil 198 | }) 199 | 200 | Handle(err) 201 | } 202 | } 203 | 204 | newOutputs := TxOutputs{} 205 | for _, out := range tx.Outputs { 206 | newOutputs.Outputs = append(newOutputs.Outputs, out) 207 | } 208 | 209 | txID := append(utxoPrefix, tx.ID...) 210 | if err := txn.Set(txID, newOutputs.Serialize()); err != nil { 211 | log.Panic(err) 212 | } 213 | } 214 | 215 | return nil 216 | }) 217 | Handle(err) 218 | } 219 | 220 | func (u *UTXOSet) DeleteByPrefix(prefix []byte) { 221 | deleteKeys := func(keysForDelete [][]byte) error { 222 | if err := u.BlockChain.Database.DB.Update(func(txn *badger.Txn) error { 223 | for _, key := range keysForDelete { 224 | if err := txn.Delete(key); err != nil { 225 | return err 226 | } 227 | } 228 | return nil 229 | }); err != nil { 230 | return err 231 | } 232 | 233 | return nil 234 | } 235 | 236 | collectSize := 100000 237 | 238 | err := u.BlockChain.Database.Iterator(false, func(it *badger.Iterator) error { 239 | keysForDelete := make([][]byte, 0, collectSize) 240 | keysCollected := 0 241 | 242 | for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { 243 | key := it.Item().KeyCopy(nil) 244 | keysForDelete = append(keysForDelete, key) 245 | keysCollected++ 246 | if keysCollected == collectSize { 247 | if err := deleteKeys(keysForDelete); err != nil { 248 | log.Panic(err) 249 | } 250 | keysForDelete = make([][]byte, 0, collectSize) 251 | keysCollected = 0 252 | } 253 | } 254 | 255 | if keysCollected > 0 { 256 | if err := deleteKeys(keysForDelete); err != nil { 257 | log.Panic(err) 258 | } 259 | } 260 | 261 | return nil 262 | }) 263 | 264 | Handle(err) 265 | } 266 | -------------------------------------------------------------------------------- /cli/cli.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "blockchain/main/blockchain" 5 | "blockchain/main/network" 6 | "blockchain/main/wallet" 7 | "flag" 8 | "fmt" 9 | "log" 10 | "os" 11 | "runtime" 12 | "strconv" 13 | ) 14 | 15 | // Responsible for processing command line arguments 16 | type CommandLine struct { 17 | } 18 | 19 | func (cli *CommandLine) printUsage() { 20 | fmt.Println("Usage:") 21 | fmt.Println(" getbalance -address ADDRESS - get the balance for an address") 22 | fmt.Println(" createblockchain -address ADDRESS creates a blockchain and sends genesis reward to address") 23 | fmt.Println(" printchain - Prints the blocks in the chain") 24 | fmt.Println(" send -from FROM -to TO -amount AMOUNT -mine - Send amount of coins. Then -mine flag is set, mine off of this node") 25 | fmt.Println(" createwallet - Creates a new Wallet") 26 | fmt.Println(" listaddresses - Lists the addresses in our wallet file") 27 | fmt.Println(" reindexutxo - Rebuilds the UTXO set") 28 | fmt.Println(" startnode -miner ADDRESS - Start a node with ID specified in NODE_ID env. var. -miner enables mining") 29 | } 30 | 31 | func (cli *CommandLine) validateArgs() { 32 | if len(os.Args) < 2 { 33 | cli.printUsage() 34 | runtime.Goexit() 35 | } 36 | } 37 | 38 | // Start node. If has miner address, start as miner 39 | func (cli *CommandLine) StartNode(nodeID, minerAddress string) { 40 | fmt.Printf("Starting Node %s\n", nodeID) 41 | 42 | if len(minerAddress) > 0 { 43 | if wallet.ValidateAddress(minerAddress) { 44 | fmt.Println("Mining is on. Address to receive rewards: ", minerAddress) 45 | } else { 46 | log.Panic("Wrong miner address!") 47 | } 48 | } 49 | 50 | network.StartServer(nodeID, minerAddress) 51 | } 52 | 53 | func (cli *CommandLine) reindexUTXO(nodeID string) { 54 | chain := blockchain.ContinueBlockChain(nodeID) 55 | defer func() { 56 | err := chain.Database.DB.Close() 57 | if err != nil { 58 | log.Panic(err) 59 | } 60 | }() 61 | 62 | UTXOSet := blockchain.UTXOSet{chain} 63 | UTXOSet.Reindex() 64 | 65 | count := UTXOSet.CountTransactions() 66 | fmt.Printf("Done! There are %d transactions in the UTXO set.\n", count) 67 | } 68 | 69 | func (cli *CommandLine) listAddresses(nodeID string) { 70 | wallets, _ := wallet.CreateWallets(nodeID) 71 | addresses := wallets.GetAllAddresses() 72 | 73 | for _, address := range addresses { 74 | fmt.Println(address) 75 | } 76 | } 77 | 78 | func (cli *CommandLine) createWallet(nodeID string) { 79 | wallets, _ := wallet.CreateWallets(nodeID) 80 | address := wallets.AddWallet() 81 | wallets.SaveFile(nodeID) 82 | 83 | fmt.Printf("New address is: %s\n", address) 84 | } 85 | 86 | func (cli *CommandLine) printChain(nodeID string) { 87 | chain := blockchain.ContinueBlockChain(nodeID) 88 | defer func() { 89 | err := chain.Database.DB.Close() 90 | if err != nil { 91 | log.Panic(err) 92 | } 93 | }() 94 | 95 | iter := chain.Iterator() 96 | 97 | for { 98 | block := iter.Next() 99 | 100 | fmt.Printf("Hash: %x\n", block.Hash) 101 | fmt.Printf("Prev. hash: %x\n", block.PrevHash) 102 | pow := blockchain.NewProof(block) 103 | fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate())) 104 | for _, tx := range block.Transactions { 105 | fmt.Println(tx) 106 | } 107 | fmt.Println() 108 | 109 | if len(block.PrevHash) == 0 { 110 | break 111 | } 112 | } 113 | } 114 | 115 | func (cli *CommandLine) createBlockChain(address, nodeID string) { 116 | if !wallet.ValidateAddress(address) { 117 | log.Panic("Address is not Valid") 118 | } 119 | 120 | chain := blockchain.InitBlockChain(address, nodeID) 121 | defer func() { 122 | err := chain.Database.DB.Close() 123 | if err != nil { 124 | log.Panic(err) 125 | } 126 | }() 127 | 128 | UTXOSet := blockchain.UTXOSet{chain} 129 | UTXOSet.Reindex() 130 | 131 | fmt.Println("Finished!") 132 | } 133 | 134 | func (cli *CommandLine) getBalance(address, nodeID string) { 135 | if !wallet.ValidateAddress(address) { 136 | log.Panic("Address is not Valid") 137 | } 138 | 139 | chain := blockchain.ContinueBlockChain(nodeID) 140 | UTXOSet := blockchain.UTXOSet{chain} 141 | defer func() { 142 | err := chain.Database.DB.Close() 143 | if err != nil { 144 | log.Panic(err) 145 | } 146 | }() 147 | 148 | balance := 0 149 | pubKeyHash := wallet.Base58Decode([]byte(address)) 150 | pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4] 151 | UTXOs := UTXOSet.FindUnspentTransactions(pubKeyHash) 152 | 153 | for _, out := range UTXOs { 154 | balance += out.Value 155 | } 156 | 157 | fmt.Printf("Balance of %s: %d\n", address, balance) 158 | } 159 | 160 | func (cli *CommandLine) send(from, to string, amount int, nodeID string, mineNow bool) { 161 | if !wallet.ValidateAddress(to) { 162 | log.Panic("Address is not Valid") 163 | } 164 | 165 | if !wallet.ValidateAddress(from) { 166 | log.Panic("Address is not Valid") 167 | } 168 | 169 | chain := blockchain.ContinueBlockChain(nodeID) 170 | 171 | UTXOSet := blockchain.UTXOSet{chain} 172 | defer func() { 173 | err := chain.Database.DB.Close() 174 | if err != nil { 175 | log.Panic(err) 176 | } 177 | }() 178 | 179 | wallets, err := wallet.CreateWallets(nodeID) 180 | if err != nil { 181 | log.Panic(err) 182 | } 183 | 184 | wal := wallets.GetWallet(from) 185 | 186 | tx := blockchain.NewTransaction(&wal, to, amount, &UTXOSet) 187 | 188 | if mineNow { 189 | cbTx := blockchain.CoinbaseTx(from, "") 190 | txs := []*blockchain.Transaction{cbTx, tx} 191 | block := chain.MineBlock(txs) 192 | UTXOSet.Update(block) 193 | } else { 194 | network.SendTx(network.KnownNodes[0], tx) 195 | } 196 | 197 | fmt.Println("Success!") 198 | } 199 | 200 | // Parse command line arguments and processes commands 201 | func (cli *CommandLine) Run() { 202 | cli.validateArgs() 203 | 204 | nodeID := os.Getenv("NODE_ID") 205 | if nodeID == "" { 206 | fmt.Printf("NODE_ID env is not set!") 207 | runtime.Goexit() 208 | } 209 | 210 | getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError) 211 | createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError) 212 | sendCmd := flag.NewFlagSet("send", flag.ExitOnError) 213 | printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError) 214 | createWalletCmd := flag.NewFlagSet("createwallet", flag.ExitOnError) 215 | listAddressesCmd := flag.NewFlagSet("listaddresses", flag.ExitOnError) 216 | reindexUTXOCmd := flag.NewFlagSet("reindexutxo", flag.ExitOnError) 217 | startNodeCmd := flag.NewFlagSet("startnode", flag.ExitOnError) 218 | 219 | getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance for") 220 | createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to send genesis block reward to") 221 | sendFrom := sendCmd.String("from", "", "Source wallet address") 222 | sendTo := sendCmd.String("to", "", "Destination wallet address") 223 | sendAmount := sendCmd.Int("amount", 0, "Amount to send") 224 | sendMine := sendCmd.Bool("mine", false, "Mine immediately on the same node") 225 | startNodeMiner := startNodeCmd.String("miner", "", "Enable mining mode and send reward to ADDRESS") 226 | 227 | switch os.Args[1] { 228 | case "reindexutxo": 229 | err := reindexUTXOCmd.Parse(os.Args[2:]) 230 | if err != nil { 231 | log.Panic(err) 232 | } 233 | case "getbalance": 234 | err := getBalanceCmd.Parse(os.Args[2:]) 235 | if err != nil { 236 | log.Panic(err) 237 | } 238 | case "createblockchain": 239 | err := createBlockchainCmd.Parse(os.Args[2:]) 240 | if err != nil { 241 | log.Panic(err) 242 | } 243 | case "startnode": 244 | err := startNodeCmd.Parse(os.Args[2:]) 245 | if err != nil { 246 | log.Panic(err) 247 | } 248 | case "listaddresses": 249 | err := listAddressesCmd.Parse(os.Args[2:]) 250 | if err != nil { 251 | log.Panic(err) 252 | } 253 | case "createwallet": 254 | err := createWalletCmd.Parse(os.Args[2:]) 255 | if err != nil { 256 | log.Panic(err) 257 | } 258 | case "printchain": 259 | err := printChainCmd.Parse(os.Args[2:]) 260 | if err != nil { 261 | log.Panic(err) 262 | } 263 | case "send": 264 | err := sendCmd.Parse(os.Args[2:]) 265 | if err != nil { 266 | log.Panic(err) 267 | } 268 | default: 269 | cli.printUsage() 270 | runtime.Goexit() 271 | } 272 | 273 | if getBalanceCmd.Parsed() { 274 | if *getBalanceAddress == "" { 275 | getBalanceCmd.Usage() 276 | runtime.Goexit() 277 | } 278 | cli.getBalance(*getBalanceAddress, nodeID) 279 | } 280 | 281 | if createBlockchainCmd.Parsed() { 282 | if *createBlockchainAddress == "" { 283 | createBlockchainCmd.Usage() 284 | runtime.Goexit() 285 | } 286 | cli.createBlockChain(*createBlockchainAddress, nodeID) 287 | } 288 | 289 | if printChainCmd.Parsed() { 290 | cli.printChain(nodeID) 291 | } 292 | 293 | if createWalletCmd.Parsed() { 294 | cli.createWallet(nodeID) 295 | } 296 | if listAddressesCmd.Parsed() { 297 | cli.listAddresses(nodeID) 298 | } 299 | if reindexUTXOCmd.Parsed() { 300 | cli.reindexUTXO(nodeID) 301 | } 302 | 303 | if sendCmd.Parsed() { 304 | if *sendFrom == "" || *sendTo == "" || *sendAmount <= 0 { 305 | sendCmd.Usage() 306 | runtime.Goexit() 307 | } 308 | 309 | cli.send(*sendFrom, *sendTo, *sendAmount, nodeID, *sendMine) 310 | } 311 | 312 | if startNodeCmd.Parsed() { 313 | nodeID := os.Getenv("NODE_ID") 314 | if nodeID == "" { 315 | startNodeCmd.Usage() 316 | runtime.Goexit() 317 | } 318 | cli.StartNode(nodeID, *startNodeMiner) 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /database/database.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "fmt" 5 | "github.com/dgraph-io/badger" 6 | "log" 7 | "os" 8 | "path/filepath" 9 | "strings" 10 | ) 11 | 12 | type Database struct { 13 | DB *badger.DB 14 | } 15 | 16 | func GetDatabase(dir string) (*Database, error) { 17 | opts := badger.DefaultOptions(dir) 18 | opts.Logger = nil 19 | 20 | if db, err := badger.Open(opts); err != nil { 21 | if strings.Contains(err.Error(), "LOCK") { 22 | if db, err := retry(dir, opts); err == nil { 23 | log.Println("database unlocked, value log truncated") 24 | return &Database{db}, nil 25 | } 26 | log.Println("could not unlock database:", err) 27 | } 28 | return nil, err 29 | } else { 30 | return &Database{db}, nil 31 | } 32 | } 33 | 34 | func (db *Database) Iterator(prefetchValues bool, fn func(*badger.Iterator) error) error { 35 | err := db.DB.View(func(txn *badger.Txn) error { 36 | 37 | opts := badger.DefaultIteratorOptions 38 | opts.PrefetchValues = prefetchValues 39 | it := txn.NewIterator(opts) 40 | defer it.Close() 41 | 42 | return fn(it) 43 | }) 44 | 45 | return err 46 | } 47 | 48 | func (db *Database) Read(key []byte) ([]byte, error) { 49 | var value []byte 50 | 51 | err := db.DB.View(func(txn *badger.Txn) error { 52 | item, err := txn.Get(key) 53 | 54 | if err != nil { 55 | return err 56 | } 57 | 58 | value, err = item.ValueCopy(nil) 59 | return err 60 | }) 61 | 62 | return value, err 63 | } 64 | 65 | func (db *Database) Update(key []byte, value []byte) error { 66 | 67 | fmt.Println("Add Key: " + string(key)) 68 | 69 | err := db.DB.Update(func(txn *badger.Txn) error { 70 | return txn.Set(key, value) 71 | }) 72 | 73 | return err 74 | } 75 | 76 | func retry(dir string, originalOpts badger.Options) (*badger.DB, error) { 77 | lockPath := filepath.Join(dir, "LOCK") 78 | if err := os.Remove(lockPath); err != nil { 79 | return nil, fmt.Errorf(`removing "LOCK": %s`, err) 80 | } 81 | retryOpts := originalOpts 82 | retryOpts.Truncate = true 83 | db, err := badger.Open(retryOpts) 84 | return db, err 85 | } 86 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "blockchain/main/cli" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | defer os.Exit(0) 10 | cmd := cli.CommandLine{} 11 | cmd.Run() 12 | } -------------------------------------------------------------------------------- /network/models.go: -------------------------------------------------------------------------------- 1 | package network 2 | 3 | type Addr struct { 4 | AddrList []string 5 | } 6 | 7 | type Block struct { 8 | AddrFrom string 9 | Block []byte 10 | } 11 | 12 | type GetBlocks struct { 13 | AddrFrom string 14 | } 15 | 16 | type GetData struct { 17 | AddrFrom string 18 | Type string 19 | ID []byte 20 | } 21 | 22 | type Inv struct { 23 | AddrFrom string 24 | Type string 25 | Items [][]byte 26 | } 27 | 28 | type Tx struct { 29 | AddrFrom string 30 | Transaction []byte 31 | } 32 | 33 | type Version struct { 34 | Version int 35 | BestHeight int 36 | AddrFrom string 37 | } 38 | -------------------------------------------------------------------------------- /network/network.go: -------------------------------------------------------------------------------- 1 | package network 2 | 3 | import ( 4 | "blockchain/main/blockchain" 5 | "bytes" 6 | "encoding/gob" 7 | "encoding/hex" 8 | "fmt" 9 | "gopkg.in/vrecan/death.v3" 10 | "io" 11 | "io/ioutil" 12 | "log" 13 | "net" 14 | "os" 15 | "runtime" 16 | "syscall" 17 | ) 18 | 19 | const ( 20 | protocol = "tcp" 21 | version = 1 22 | commandLength = 12 23 | ) 24 | 25 | var ( 26 | nodeAddress string 27 | mineAddress string 28 | KnownNodes = []string{"localhost:3000"} 29 | blocksInTransit [][]byte 30 | memoryPool = make(map[string]blockchain.Transaction) 31 | ) 32 | 33 | func RequestBlocks() { 34 | for _, node := range KnownNodes { 35 | SendGetBlocks(node) 36 | } 37 | } 38 | 39 | func SendBlock(addr string, b *blockchain.Block) { 40 | fmt.Println("Send block command: " + addr) 41 | 42 | data := Block{nodeAddress, b.Serialize()} 43 | payload := GobEncode(data) 44 | request := append(CmdToBytes("block"), payload...) 45 | 46 | SendData(addr, request) 47 | } 48 | 49 | func SendData(addr string, data []byte) { 50 | conn, err := net.Dial(protocol, addr) 51 | 52 | if err != nil { 53 | fmt.Printf("%s is not available\n", addr) 54 | var updatedNodes []string 55 | 56 | for _, node := range KnownNodes { 57 | if node != addr { 58 | updatedNodes = append(updatedNodes, node) 59 | } 60 | } 61 | 62 | KnownNodes = updatedNodes 63 | 64 | return 65 | } 66 | 67 | defer func() { 68 | err := conn.Close() 69 | if err != nil { 70 | log.Panic(err) 71 | } 72 | }() 73 | 74 | _, err = io.Copy(conn, bytes.NewReader(data)) 75 | if err != nil { 76 | log.Panic(err) 77 | } 78 | } 79 | 80 | func SendInv(address, kind string, items [][]byte) { 81 | fmt.Println("Send get Inv command: " + address + " kind: " + kind) 82 | 83 | inventory := Inv{nodeAddress, kind, items} 84 | payload := GobEncode(inventory) 85 | request := append(CmdToBytes("inv"), payload...) 86 | 87 | SendData(address, request) 88 | } 89 | 90 | func SendGetBlocks(address string) { 91 | fmt.Println("Send get blocks command: " + address) 92 | 93 | payload := GobEncode(GetBlocks{nodeAddress}) 94 | request := append(CmdToBytes("getblocks"), payload...) 95 | 96 | SendData(address, request) 97 | } 98 | 99 | func SendGetData(address, kind string, id []byte) { 100 | fmt.Println("Send get data command: " + address + " kind:" + kind) 101 | 102 | payload := GobEncode(GetData{nodeAddress, kind, id}) 103 | request := append(CmdToBytes("getdata"), payload...) 104 | 105 | SendData(address, request) 106 | } 107 | 108 | func SendTx(addr string, tnx *blockchain.Transaction) { 109 | fmt.Println("Send Tx command: " + addr + " Tx: " + hex.EncodeToString(tnx.ID)) 110 | 111 | data := Tx{nodeAddress, tnx.Serialize()} 112 | payload := GobEncode(data) 113 | request := append(CmdToBytes("tx"), payload...) 114 | 115 | SendData(addr, request) 116 | } 117 | 118 | func SendVersion(addr string, chain *blockchain.BlockChain) { 119 | fmt.Println("Send version command: " + addr) 120 | 121 | bestHeight := chain.GetBestHeight() 122 | payload := GobEncode(Version{version, bestHeight, nodeAddress}) 123 | 124 | request := append(CmdToBytes("version"), payload...) 125 | 126 | SendData(addr, request) 127 | } 128 | 129 | func HandleAddr(request []byte) { 130 | var buff bytes.Buffer 131 | var payload Addr 132 | 133 | buff.Write(request[commandLength:]) 134 | dec := gob.NewDecoder(&buff) 135 | 136 | err := dec.Decode(&payload) 137 | if err != nil { 138 | log.Panic(err) 139 | 140 | } 141 | 142 | KnownNodes = append(KnownNodes, payload.AddrList...) 143 | fmt.Printf("there are %d known nodes\n", len(KnownNodes)) 144 | RequestBlocks() 145 | } 146 | 147 | func HandleBlock(request []byte, chain *blockchain.BlockChain) { 148 | var buff bytes.Buffer 149 | var payload Block 150 | 151 | buff.Write(request[commandLength:]) 152 | dec := gob.NewDecoder(&buff) 153 | err := dec.Decode(&payload) 154 | if err != nil { 155 | log.Panic(err) 156 | } 157 | 158 | blockData := payload.Block 159 | block := blockchain.Deserialize(blockData) 160 | 161 | fmt.Println("Received a new block!") 162 | chain.AddBlock(block) 163 | 164 | fmt.Printf("Added block %x\n", block.Hash) 165 | 166 | if len(blocksInTransit) > 0 { 167 | blockHash := blocksInTransit[0] 168 | SendGetData(payload.AddrFrom, "block", blockHash) 169 | 170 | blocksInTransit = blocksInTransit[1:] 171 | } else { 172 | UTXOSet := blockchain.UTXOSet{chain} 173 | UTXOSet.Reindex() 174 | } 175 | } 176 | 177 | func HandleInv(request []byte) { 178 | var buff bytes.Buffer 179 | var payload Inv 180 | 181 | buff.Write(request[commandLength:]) 182 | dec := gob.NewDecoder(&buff) 183 | 184 | err := dec.Decode(&payload) 185 | if err != nil { 186 | log.Panic(err) 187 | } 188 | 189 | fmt.Printf("[Handle Inv] With %d, Type: %s\n", len(payload.Items), payload.Type) 190 | 191 | if payload.Type == "block" { 192 | blocksInTransit = payload.Items 193 | 194 | blockHash := payload.Items[0] 195 | SendGetData(payload.AddrFrom, "block", blockHash) 196 | 197 | var newInTransit [][]byte 198 | for _, b := range blocksInTransit { 199 | if bytes.Compare(b, blockHash) != 0 { 200 | newInTransit = append(newInTransit, b) 201 | } 202 | } 203 | 204 | blocksInTransit = newInTransit 205 | } 206 | 207 | if payload.Type == "tx" { 208 | txID := payload.Items[0] 209 | 210 | if memoryPool[hex.EncodeToString(txID)].ID == nil { 211 | SendGetData(payload.AddrFrom, "tx", txID) 212 | } 213 | } 214 | } 215 | 216 | func HandleGetBlocks(request []byte, chain *blockchain.BlockChain) { 217 | fmt.Println("Handling Get Blocks.") 218 | 219 | var buff bytes.Buffer 220 | var payload GetBlocks 221 | 222 | buff.Write(request[commandLength:]) 223 | dec := gob.NewDecoder(&buff) 224 | 225 | err := dec.Decode(&payload) 226 | if err != nil { 227 | log.Panic(err) 228 | } 229 | 230 | blocks := chain.GetBlockHashes() 231 | SendInv(payload.AddrFrom, "block", blocks) 232 | } 233 | 234 | func HandleGetData(request []byte, chain *blockchain.BlockChain) { 235 | var buff bytes.Buffer 236 | var payload GetData 237 | 238 | buff.Write(request[commandLength:]) 239 | dec := gob.NewDecoder(&buff) 240 | err := dec.Decode(&payload) 241 | if err != nil { 242 | log.Panic(err) 243 | } 244 | 245 | fmt.Printf("Handle Get Data: %s, Type: %s\n", payload.AddrFrom, payload.Type) 246 | 247 | if payload.Type == "block" { 248 | block, err := chain.GetBlock([]byte(payload.ID)) 249 | if err != nil { 250 | return 251 | } 252 | 253 | SendBlock(payload.AddrFrom, &block) 254 | } 255 | 256 | if payload.Type == "tx" { 257 | txID := hex.EncodeToString(payload.ID) 258 | tx := memoryPool[txID] 259 | 260 | SendTx(payload.AddrFrom, &tx) 261 | } 262 | } 263 | 264 | func HandleTx(request []byte, chain *blockchain.BlockChain) { 265 | var buff bytes.Buffer 266 | var payload Tx 267 | 268 | buff.Write(request[commandLength:]) 269 | dec := gob.NewDecoder(&buff) 270 | 271 | err := dec.Decode(&payload) 272 | if err != nil { 273 | log.Panic(err) 274 | } 275 | 276 | txData := payload.Transaction 277 | tx := blockchain.DeserializeTransaction(txData) 278 | memoryPool[hex.EncodeToString(tx.ID)] = tx 279 | 280 | fmt.Printf("[Handle Tx] From: %s, MemoryPool Size: %d\n", payload.AddrFrom, len(memoryPool)) 281 | 282 | if nodeAddress == KnownNodes[0] { 283 | for _, node := range KnownNodes { 284 | if node != nodeAddress && node != payload.AddrFrom { 285 | SendInv(node, "tx", [][]byte{tx.ID}) 286 | } 287 | } 288 | } else { 289 | fmt.Println("Waiting more transactions to mine.") 290 | if len(memoryPool) >= 2 && len(mineAddress) > 0 { 291 | fmt.Println("Starting mining..") 292 | MineTx(chain) 293 | } 294 | } 295 | } 296 | 297 | func MineTx(chain *blockchain.BlockChain) { 298 | var txs []*blockchain.Transaction 299 | 300 | for id := range memoryPool { 301 | tx := memoryPool[id] 302 | 303 | if chain.VerifyTransaction(&tx) { 304 | txs = append(txs, &tx) 305 | } 306 | } 307 | 308 | if len(txs) == 0 { 309 | fmt.Println("All Transactions are invalid") 310 | return 311 | } 312 | 313 | cbTx := blockchain.CoinbaseTx(mineAddress, "") 314 | txs = append(txs, cbTx) 315 | 316 | newBlock := chain.MineBlock(txs) 317 | UTXOSet := blockchain.UTXOSet{chain} 318 | UTXOSet.Reindex() 319 | 320 | fmt.Println("New Block mined") 321 | 322 | for _, tx := range txs { 323 | txID := hex.EncodeToString(tx.ID) 324 | delete(memoryPool, txID) 325 | } 326 | 327 | for _, node := range KnownNodes { 328 | if node != nodeAddress { 329 | SendInv(node, "block", [][]byte{newBlock.Hash}) 330 | } 331 | } 332 | 333 | if len(memoryPool) > 0 { 334 | MineTx(chain) 335 | } 336 | } 337 | 338 | func HandleVersion(request []byte, chain *blockchain.BlockChain) { 339 | var buff bytes.Buffer 340 | var payload Version 341 | 342 | buff.Write(request[commandLength:]) 343 | dec := gob.NewDecoder(&buff) 344 | 345 | err := dec.Decode(&payload) 346 | if err != nil { 347 | log.Panic(err) 348 | } 349 | 350 | bestHeight := chain.GetBestHeight() 351 | otherHeight := payload.BestHeight 352 | 353 | fmt.Printf("Handling Version from: %s, Version: %d, BestHeight: %d, OtherBestHeight: %d\n", 354 | payload.AddrFrom, payload.Version, bestHeight, otherHeight) 355 | 356 | if bestHeight < otherHeight { 357 | SendGetBlocks(payload.AddrFrom) 358 | } else if bestHeight > otherHeight { 359 | SendVersion(payload.AddrFrom, chain) 360 | } 361 | 362 | // Add new node to known nodes 363 | if !NodeIsKnown(payload.AddrFrom) { 364 | KnownNodes = append(KnownNodes, payload.AddrFrom) 365 | } 366 | } 367 | 368 | func HandleConnection(conn net.Conn, chain *blockchain.BlockChain) { 369 | req, err := ioutil.ReadAll(conn) 370 | 371 | if err != nil { 372 | log.Panic(err) 373 | } 374 | 375 | command := BytesToCmd(req[:commandLength]) 376 | fmt.Printf("Received %s command\n", command) 377 | 378 | switch command { 379 | case "addr": 380 | HandleAddr(req) 381 | case "block": 382 | HandleBlock(req, chain) 383 | case "inv": 384 | HandleInv(req) 385 | case "getblocks": 386 | HandleGetBlocks(req, chain) 387 | case "getdata": 388 | HandleGetData(req, chain) 389 | case "tx": 390 | HandleTx(req, chain) 391 | case "version": 392 | HandleVersion(req, chain) 393 | default: 394 | fmt.Println("Unknown command") 395 | } 396 | 397 | } 398 | 399 | func StartServer(nodeID, minerAddress string) { 400 | nodeAddress = fmt.Sprintf("localhost:%s", nodeID) 401 | mineAddress = minerAddress 402 | 403 | ln, err := net.Listen(protocol, nodeAddress) 404 | 405 | if err != nil { 406 | log.Panic(err) 407 | } 408 | 409 | defer func() { 410 | err := ln.Close() 411 | if err != nil { 412 | log.Panic(err) 413 | } 414 | }() 415 | 416 | chain := blockchain.ContinueBlockChain(nodeID) 417 | defer func() { 418 | err := chain.Database.DB.Close() 419 | if err != nil { 420 | log.Panic(err) 421 | } 422 | }() 423 | 424 | go CloseDB(chain) 425 | 426 | if nodeAddress != KnownNodes[0] { 427 | SendVersion(KnownNodes[0], chain) 428 | } 429 | 430 | for { 431 | conn, err := ln.Accept() 432 | if err != nil { 433 | log.Panic(err) 434 | } 435 | go HandleConnection(conn, chain) 436 | 437 | } 438 | } 439 | 440 | func NodeIsKnown(addr string) bool { 441 | for _, node := range KnownNodes { 442 | if node == addr { 443 | return true 444 | } 445 | } 446 | 447 | return false 448 | } 449 | 450 | func CloseDB(chain *blockchain.BlockChain) { 451 | d := death.NewDeath(syscall.SIGINT, syscall.SIGTERM, os.Interrupt) 452 | 453 | d.WaitForDeathWithFunc(func() { 454 | defer os.Exit(1) 455 | defer runtime.Goexit() 456 | 457 | err := chain.Database.DB.Close() 458 | if err != nil { 459 | log.Panic(err) 460 | } 461 | }) 462 | } 463 | -------------------------------------------------------------------------------- /network/util.go: -------------------------------------------------------------------------------- 1 | package network 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | "fmt" 7 | "log" 8 | ) 9 | 10 | // Transform command strings to byte array 11 | func CmdToBytes(cmd string) []byte { 12 | var data [commandLength]byte 13 | 14 | for i, c := range cmd { 15 | data[i] = byte(c) 16 | } 17 | 18 | return data[:] 19 | } 20 | 21 | // Transform byte array to command string 22 | func BytesToCmd(bytes []byte) string { 23 | var cmd []byte 24 | 25 | for _, b := range bytes { 26 | if b != 0x0 { 27 | cmd = append(cmd, b) 28 | } 29 | } 30 | 31 | return fmt.Sprintf("%s", cmd) 32 | } 33 | 34 | // Encode data 35 | func GobEncode(data interface{}) []byte { 36 | var buff bytes.Buffer 37 | 38 | enc := gob.NewEncoder(&buff) 39 | err := enc.Encode(data) 40 | if err != nil { 41 | log.Panic(err) 42 | } 43 | 44 | return buff.Bytes() 45 | } 46 | -------------------------------------------------------------------------------- /wallet/utils.go: -------------------------------------------------------------------------------- 1 | package wallet 2 | 3 | import ( 4 | "github.com/mr-tron/base58" 5 | "log" 6 | ) 7 | 8 | func Base58Encode(input []byte) []byte { 9 | encode := base58.Encode(input) 10 | 11 | return []byte(encode) 12 | } 13 | 14 | func Base58Decode(input []byte) []byte { 15 | decode, err := base58.Decode(string(input[:])) 16 | if err != nil { 17 | log.Panic(err) 18 | } 19 | 20 | return decode 21 | } 22 | -------------------------------------------------------------------------------- /wallet/wallet.go: -------------------------------------------------------------------------------- 1 | package wallet 2 | 3 | import ( 4 | "bytes" 5 | "crypto/ecdsa" 6 | "crypto/elliptic" 7 | "crypto/rand" 8 | "crypto/sha256" 9 | "log" 10 | 11 | "golang.org/x/crypto/ripemd160" 12 | ) 13 | 14 | const ( 15 | checksumLength = 4 16 | version = byte(0x00) 17 | ) 18 | 19 | type Wallet struct { 20 | PrivateKey ecdsa.PrivateKey 21 | PublicKey []byte 22 | } 23 | 24 | func (w Wallet) Address() []byte { 25 | // Returns RIPEMD-160 hash 26 | pubHash := PublicKeyHash(w.PublicKey) 27 | 28 | // Add version byte in front of RIPEMD-160 hash 29 | versionedHash := append([]byte{version}, pubHash...) 30 | 31 | // Get 4 bytes checksum 32 | checksum := Checksum(versionedHash) 33 | 34 | // Add the 4 checksum bytes at the end of extended RIPEMD-160 hash 35 | // This is the 25-byte binary wallet address 36 | fullHash := append(versionedHash, checksum...) 37 | 38 | // Convert the result from a byte string into a base58 string 39 | address := Base58Encode(fullHash) 40 | return address 41 | } 42 | 43 | func ValidateAddress(address string) bool { 44 | // Decode Base58 address string 45 | pubKeyHash := Base58Decode([]byte(address)) 46 | 47 | // Get actual checksum bytes 48 | actualChecksum := pubKeyHash[len(pubKeyHash)-checksumLength:] 49 | 50 | version := pubKeyHash[0] 51 | 52 | // Remove the version and checksum bytes 53 | pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-checksumLength] 54 | 55 | // Get 4 bytes checksum 56 | targetChecksum := Checksum(append([]byte{version}, pubKeyHash...)) 57 | 58 | // Compare actual and true checksum bytes 59 | return bytes.Compare(actualChecksum, targetChecksum) == 0 60 | } 61 | 62 | func NewKeyPair() (ecdsa.PrivateKey, []byte) { 63 | // Create an elliptic curve 64 | curve := elliptic.P256() 65 | 66 | // Generate private ECDSA key 67 | private, err := ecdsa.GenerateKey(curve, rand.Reader) 68 | if err != nil { 69 | log.Panic(err) 70 | } 71 | 72 | // Take the corresponding public key generated with it 73 | pub := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...) 74 | return *private, pub 75 | } 76 | 77 | func MakeWallet() *Wallet { 78 | private, public := NewKeyPair() 79 | wallet := Wallet{private, public} 80 | 81 | return &wallet 82 | } 83 | 84 | func PublicKeyHash(pubKey []byte) []byte { 85 | // Perform SHA-256 hashing on the public key 86 | pubHash := sha256.Sum256(pubKey) 87 | 88 | // Perform RIPEMD-160 hashing on the result of SHA-256 89 | hasher := ripemd160.New() 90 | 91 | _, err := hasher.Write(pubHash[:]) 92 | if err != nil { 93 | log.Panic(err) 94 | } 95 | 96 | publicRipEMD := hasher.Sum(nil) 97 | return publicRipEMD 98 | } 99 | 100 | func Checksum(payload []byte) []byte { 101 | // Perform SHA-256 hash on the extended RIPEMD-160 hash 102 | firstHash := sha256.Sum256(payload) 103 | 104 | // Perform SHA-256 hash on the result of the previous SHA-256 hash 105 | secondHash := sha256.Sum256(firstHash[:]) 106 | 107 | // Take the first 4 bytes of the second SHA-256 hash. This is the address checksum 108 | return secondHash[:checksumLength] 109 | } 110 | -------------------------------------------------------------------------------- /wallet/wallets.go: -------------------------------------------------------------------------------- 1 | package wallet 2 | 3 | import ( 4 | "bytes" 5 | "crypto/elliptic" 6 | "encoding/gob" 7 | "fmt" 8 | "io/ioutil" 9 | "log" 10 | "os" 11 | ) 12 | 13 | const walletFile = "/tmp/wallets_%s.data" 14 | 15 | type Wallets struct { 16 | Wallets map[string]*Wallet 17 | } 18 | 19 | func CreateWallets(nodeId string) (*Wallets, error) { 20 | wallets := Wallets{} 21 | wallets.Wallets = make(map[string]*Wallet) 22 | 23 | err := wallets.LoadFile(nodeId) 24 | 25 | return &wallets, err 26 | } 27 | 28 | func (ws *Wallets) AddWallet() string { 29 | wallet := MakeWallet() 30 | address := fmt.Sprintf("%s", wallet.Address()) 31 | 32 | ws.Wallets[address] = wallet 33 | 34 | return address 35 | } 36 | 37 | func (ws *Wallets) GetAllAddresses() []string { 38 | var addresses []string 39 | 40 | for address := range ws.Wallets { 41 | addresses = append(addresses, address) 42 | } 43 | 44 | return addresses 45 | } 46 | 47 | func (ws Wallets) GetWallet(address string) Wallet { 48 | return *ws.Wallets[address] 49 | } 50 | 51 | func (ws *Wallets) LoadFile(nodeId string) error { 52 | walletFile := fmt.Sprintf(walletFile, nodeId) 53 | if _, err := os.Stat(walletFile); os.IsNotExist(err) { 54 | return err 55 | } 56 | 57 | var wallets Wallets 58 | 59 | fileContent, err := ioutil.ReadFile(walletFile) 60 | if err != nil { 61 | return err 62 | } 63 | 64 | gob.Register(elliptic.P256()) 65 | decoder := gob.NewDecoder(bytes.NewReader(fileContent)) 66 | err = decoder.Decode(&wallets) 67 | if err != nil { 68 | return err 69 | } 70 | 71 | ws.Wallets = wallets.Wallets 72 | 73 | return nil 74 | } 75 | 76 | func (ws *Wallets) SaveFile(nodeId string) { 77 | var content bytes.Buffer 78 | walletFile := fmt.Sprintf(walletFile, nodeId) 79 | 80 | gob.Register(elliptic.P256()) 81 | 82 | encoder := gob.NewEncoder(&content) 83 | err := encoder.Encode(ws) 84 | if err != nil { 85 | log.Panic(err) 86 | } 87 | 88 | err = ioutil.WriteFile(walletFile, content.Bytes(), 0644) 89 | if err != nil { 90 | log.Panic(err) 91 | } 92 | } --------------------------------------------------------------------------------