-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.go
55 lines (42 loc) · 1013 Bytes
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package kcoin
import (
"bytes"
"crypto/sha256"
"time"
)
const genesisCoinbaseData = "Kamal Genesis Block"
type Block struct {
Timestamp int64
Transactions []*Transaction
PrevBlockHash []byte
Hash []byte
Nonce int64
}
func (block *Block) HashTransactions() []byte {
var txHashes [][]byte
for _, tx := range block.Transactions {
txHashes = append(txHashes, tx.ID)
}
resultHash := sha256.Sum256(bytes.Join(txHashes, []byte{}))
return resultHash[:]
}
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{
Timestamp: time.Now().Unix(),
Transactions: transactions,
PrevBlockHash: prevBlockHash,
Hash: []byte{},
Nonce: 0,
}
proofOfWork := NewProofOfWork(block)
nonce, hash, err := proofOfWork.Mine()
if err != nil {
panic(err)
}
block.Hash = hash
block.Nonce = nonce
return block
}
func NewGenesisBlock(coinbase *Transaction) *Block {
return NewBlock([]*Transaction{coinbase}, []byte{})
}