/
mining.go
209 lines (185 loc) · 5.28 KB
/
mining.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package mining
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
"github.com/mitchellh/hashstructure"
)
const (
timeFormat = "2006-01-02T15:04:05.000Z0700"
clockSkewMin = 5
)
var (
latestDataQueue = []uint64{}
queuedDataMap = map[uint64]*BlockData{}
queuedDataMapLock sync.Mutex
// BlockProcessedChan is a channel for indicating blocks have been processed
BlockProcessedChan = make(chan int)
)
// BlockData is the data for a block
type BlockData struct {
Timestamp string
PublicKey string
Signature string
ProjectID string
CommitHash string
FileHashes map[string]string
MetaData map[string]string
}
// Block keeps block headers
type Block struct {
Data BlockData
PrevBlockHash string
Hash string
}
// Blockchain keeps a sequence of Blocks
type Blockchain struct {
Blocks []*Block
StagedBlock *Block
}
func (b *Block) setHash() {
b.Hash = b.ComputeHash()
}
// ComputeHash calculates the block hash
func (b *Block) ComputeHash() string {
dHash, _ := hashstructure.Hash(b.Data, nil)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, dHash)
hash := sha256.Sum256(append([]byte(b.PrevBlockHash), bytes...))
return hex.EncodeToString(hash[:])
}
// NewBlock creates and returns Block
func NewBlock(data BlockData, prevBlockHash string) *Block {
block := &Block{Data: data, PrevBlockHash: prevBlockHash}
block.setHash()
return block
}
// NewGenesisBlock creates and returns genesis Block
func NewGenesisBlock() *Block {
return NewBlock(BlockData{
Timestamp: "",
PublicKey: "",
Signature: "ProSe",
ProjectID: "",
CommitHash: "421fdea6ec87b5531d196bb7498c96fb84f2880a",
FileHashes: map[string]string{},
MetaData: map[string]string{},
}, "")
}
// StageBlock stages a block
func (bc *Blockchain) StageBlock(b *Block) {
bc.StagedBlock = b
}
// Commit commits a staged block to the blockchain
func (bc *Blockchain) Commit() (err error) {
if bc.StagedBlock == nil {
return errors.New("no staged block")
}
bc.Blocks = append(bc.Blocks, bc.StagedBlock)
bc.StagedBlock = nil
select {
case BlockProcessedChan <- 1:
default:
}
return
}
// ProcessNewBlock saves provided data as a block in the blockchain
func (bc *Blockchain) ProcessNewBlock(data BlockData) *Block {
prevBlock := bc.Blocks[len(bc.Blocks)-1]
newBlock := NewBlock(data, prevBlock.Hash)
bc.StageBlock(newBlock)
return newBlock
}
// NewBlockchain creates a new Blockchain with genesis Block
func NewBlockchain() *Blockchain {
return &Blockchain{Blocks: []*Block{NewGenesisBlock()}}
}
// IsBlockDataQueued returns true if block data is queued
func IsBlockDataQueued(data *BlockData) bool {
queuedDataMapLock.Lock()
defer queuedDataMapLock.Unlock()
dHash, _ := hashstructure.Hash(data, nil)
_, ok := queuedDataMap[dHash]
return ok
}
// RemoveTransactionData removes the specified transaction data
// TODO: may want to be more efficient here
func RemoveTransactionData(data *BlockData) (err error) {
queuedDataMapLock.Lock()
defer queuedDataMapLock.Unlock()
dHash, _ := hashstructure.Hash(data, nil)
if len(latestDataQueue) == 0 {
err = errors.New("queue is already empty")
return
}
tmp := latestDataQueue[:0]
for _, h := range latestDataQueue {
if h != dHash {
tmp = append(tmp, h)
}
}
latestDataQueue = tmp
if _, ok := queuedDataMap[dHash]; !ok {
err = errors.New("data not found in map")
return
}
delete(queuedDataMap, dHash)
return
}
// PeekLatestTransactionData returns the latest transaction data
func PeekLatestTransactionData() (data *BlockData, err error) {
if len(latestDataQueue) == 0 {
err = errors.New("tried peeking from empty queue")
return
}
dHash := latestDataQueue[0]
data = queuedDataMap[dHash]
return
}
// EnqueueTransactionData enqueues the latest transaction data
func EnqueueTransactionData(data *BlockData) {
queuedDataMapLock.Lock()
defer queuedDataMapLock.Unlock()
dHash, _ := hashstructure.Hash(data, nil)
queuedDataMap[dHash] = data
latestDataQueue = append(latestDataQueue, dHash)
}
// NewTransactionDataExists returns true if there is enqueued transaction data
func NewTransactionDataExists() bool {
return len(latestDataQueue) > 0
}
// TimeToString returns the string representation of a time
func TimeToString(t time.Time) string {
return t.Format(timeFormat)
}
// StringToTime returns the time representation of a string
func StringToTime(s string) (t time.Time, err error) {
t, err = time.Parse(timeFormat, s)
return
}
// IsBlockValid determines if the newBlock is a valid successor to oldBlock
func (bc *Blockchain) IsBlockValid(block *Block) error {
prevHash := bc.Blocks[len(bc.Blocks)-1].Hash
if block.PrevBlockHash != prevHash {
return fmt.Errorf("block failed validation for prev hash: expected %s but got %s", prevHash, block.PrevBlockHash)
}
hash := block.ComputeHash()
if block.Hash != hash {
return fmt.Errorf("Block failed validation for hash: expected %s but got %s", hash, block.Hash)
}
t, err := StringToTime(block.Data.Timestamp)
if err != nil {
return fmt.Errorf("failed to parse time %s", block.Data.Timestamp)
}
now := time.Now().UTC()
if now.Sub(t).Minutes() > clockSkewMin {
return fmt.Errorf("block failed validation for clock skew: %s does not fall within %d minutes of %s",
block.Data.Timestamp,
clockSkewMin, TimeToString(now))
}
return nil
}