-
Notifications
You must be signed in to change notification settings - Fork 0
/
blocks.js
228 lines (184 loc) · 6.48 KB
/
blocks.js
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import Joi from 'joi'
import sha256 from 'sha256'
import _ from 'lodash'
import dotenv from 'dotenv'
dotenv.config()
import canonicalize from './canonicalize.js'
import { logger, colorizeBlockManager } from './logger.js'
import { TransactionManager } from './transactions.js'
const TARGET_T = '00000002af000000000000000000000000000000000000000000000000000000'
export const GENESIS_BLOCK_HASH = '00000000a420b7cefa2b7730243316921ed59ffe836e111ca3801f82a4f5360e'
const blockSchema = Joi.object({
txids: Joi.array().items(Joi.string().hex()),
nonce: Joi.string().hex(),
previd: Joi.string().hex().allow(null),
created: Joi.number().integer(),
T: Joi.string().valid(TARGET_T),
miner: Joi.string().optional(),
note: Joi.string().optional()
})
export class BlockManager {
transactionManager
constructor() {
this.logger = this.logger.bind(this)
this.transactionManager = new TransactionManager
this.getBlockHash = this.getBlockHash.bind(this)
this.getBlockObject = this.getBlockObject.bind(this)
}
async validateBlockTransactions({ block, getObject, UTXO, height }) {
let currentUTXO = _.clone(UTXO)
const transactions = []
for (const txid of block.txids) {
this.logger('Requesting transaction: %O', txid)
let transaction
try {
transaction = await getObject(txid)
this.logger('Got this transaction: %O', transaction)
transactions.push(transaction)
} catch (e) {
this.logger('There was an error with transaction: %O', txid)
this.logger('Failed block transaction validation')
return false
}
}
if (transactions.length === 0) {
this.logger('No transactions in this block')
return currentUTXO
}
const coinbaseTransaction = transactions[0]
if (this.transactionManager.validateCoinbaseTransactionSchema(coinbaseTransaction)) {
this.logger('This block has a coinbase transaction')
transactions.splice(0, 1) //remove the coinbase transaction from the rest of the transactions
currentUTXO = this.transactionManager.getNewUTXO({ UTXO: currentUTXO, transaction: coinbaseTransaction })
this.logger('New UTXO: %O', currentUTXO)
if (!this.transactionManager.validateCoinbaseTransaction({ coinbaseTransaction, normalTransactions: transactions, UTXO: currentUTXO, height })) {
this.logger('Incorrect coinbase transaction for this block')
return false
}
} else {
this.logger('This block does not have a coinbase transaction or it does not have a valid one')
}
for (const transaction of transactions) {
const isTransactionValid = this.transactionManager.validateTransaction({ UTXO: currentUTXO, transaction })
if (!isTransactionValid) {
this.logger('Failed block transaction validation')
return false
}
currentUTXO = this.transactionManager.getNewUTXO({ UTXO: currentUTXO, transaction })
this.logger('New UTXO: %O', currentUTXO)
}
this.logger('Block transactions successfully validated')
return currentUTXO
}
getBlockObject(block) {
const blockObject = {
type: 'block',
txids: block.txids,
nonce: block.nonce,
previd: block.previd,
created: block.created,
T: block.T
}
if (block.miner) {
blockObject.miner = block.miner
}
if (block.note) {
blockObject.note = block.note
}
return blockObject
}
getBlockHash(block) {
const blockObject = this.getBlockObject(block)
return sha256(canonicalize(blockObject))
}
validatePoW(block) {
const blockHash = this.getBlockHash(block)
this.logger('Block hash is: %O', blockHash)
if (blockHash >= TARGET_T) {
this.logger('Block does not satisfy PoW')
return false
}
this.logger('Block satisfies PoW')
return true
}
validateBlockSchema(block) {
const schemaValidation = blockSchema.validate(block)
if (schemaValidation.error) {
this.logger('Block schema validation failed with error: %O', schemaValidation.error)
return false
}
this.logger('Successfully validated block schema for block: %O', this.getBlockHash(block))
return true
}
isGenesisBlock(block) {
const blockObject = this.getBlockObject(block)
const blockHash = sha256(canonicalize(blockObject))
if (blockHash === GENESIS_BLOCK_HASH) {
this.logger('Found the genesis block')
}
return blockHash === GENESIS_BLOCK_HASH
}
async validateBlock({ block, getObject }) {
this.logger('Now validating block: %O', block)
if (!this.validateBlockSchema(block)) {
return false
}
if (this.isGenesisBlock(block)) {
return { UTXO: {}, height: 1 }
}
if (!block.previd) {
this.logger('Wrong genesis block: %O', this.getBlockHash(block))
return false
}
if (!this.validatePoW(block) && !process.env.JEST_WORKER_ID) {
return false
}
this.logger('Requesting previous block: %O', block.previd)
let previousBlock
try {
previousBlock = await getObject(block.previd)
this.logger('Got this previous block: %O', previousBlock)
} catch (e) {
this.logger('There was an error with the promise of the previous block: %O %O', block.previd, e)
return false
}
if (block.created < previousBlock.created) {
this.logger('Block timestamp is not ascending')
return false
}
let validatedBlockInfo = await this.validateBlock({ block: previousBlock, getObject })
if (!validatedBlockInfo) {
this.logger('Failed validation for block: %O', this.getBlockHash(block))
return false
}
validatedBlockInfo.UTXO = await this.validateBlockTransactions({ block, getObject, UTXO: validatedBlockInfo.UTXO, height: validatedBlockInfo.height + 1 })
this.logger('Current UTXO: %O', validatedBlockInfo.UTXO)
if (!validatedBlockInfo.UTXO) {
this.logger('Failed transaction validation for block: %O', this.getBlockHash(block))
return false
}
this.logger('Successfully validated block: %O', this.getBlockHash(block))
return { UTXO: validatedBlockInfo.UTXO, height: validatedBlockInfo.height + 1 }
}
logger(message, ...args) {
logger.info(`${colorizeBlockManager()}: ${message}`, ...args)
}
}
export class Block {
txids = []
nonce
previd
created
T
miner
note
constructor(block) {
this.txids = block.txids
this.nonce = block.nonce
this.previd = block.previd
this.created = block.created
this.T = block.T
this.miner = block.miner
this.note = block.note
}
}