-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.go
More file actions
109 lines (91 loc) · 1.96 KB
/
block.go
File metadata and controls
109 lines (91 loc) · 1.96 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* @Author: ASlowPerson
* @Date: 19-6-26 下午4:34
*/
package main
import (
"bytes"
"encoding/gob"
"fmt"
"time"
)
/*
定义区块结构
第一阶段: 先实现基础字段:前区块哈希,哈希,数据
第二阶段: 补充字段:Version,时间戳,难度值等
*/
type Block struct {
// 版本号
Version uint64
// 前区块哈希
PrevHash []byte
// 交易的根哈希值
MerkleRoot []byte
// 时间戳
TimeStamp uint64
// 难度值, 系统提供一个数据,用于计算出一个哈希值
Bits uint64
// 随机数,挖矿要求的数值
Nonce uint64
// 当前区块的哈希,为了方便,将当前区块的哈希也放入Block中
Hash []byte
// 交易集合,一个区块可以有多个交易
Transactions []*Transaction
}
/*
定义创建一个区块的函数
输入:数据,前区块的哈希值
输出:区块
*/
func NewBlock(txs []*Transaction, prevHash []byte) *Block {
b := Block{
Version: 0,
PrevHash: prevHash,
MerkleRoot: nil,
TimeStamp: uint64(time.Now().Unix()),
Bits: 0,
Nonce: 0,
Hash: nil,
Transactions: txs,
}
// 将pow集成到Block中
pow := NewProofofWork(&b)
hash, nonce := pow.Run()
b.Hash = hash
b.Nonce = nonce
return &b
}
/*
定义序列化方法,使用gob编码,将block序列化
gob编码,go语言内置编解码包,可以支持变长类型的编解码(通用)
*/
func (b *Block) Serialize() []byte {
// 编码
var buffer bytes.Buffer
// 1.创建编码器
encoder := gob.NewEncoder(&buffer)
// 2.编码
err := encoder.Encode(&b)
if err != nil {
fmt.Printf("encode err:", err)
return nil
}
return buffer.Bytes()
}
/*
定义反序列化方法
输入[]byte,返回block
*/
func Deserialize(src []byte) *Block {
// 解码
var block Block
// 1.创建解码器
decoder := gob.NewDecoder(bytes.NewReader(src))
// 2.解码
err := decoder.Decode(&block)
if err != nil {
fmt.Printf("Decode err:", err)
return nil
}
return &block
}