Repository navigation
Expand file tree
/
Copy pathblockchain.js
More file actions
219 lines (183 loc) · 5.96 KB
/
Copy pathblockchain.js
File metadata and controls
219 lines (183 loc) · 5.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
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
// const Block = require("./block.js")
// const rocksdb = require("rocksdb")
// const fs = require("node:fs");
// const [Transaction, NewCoinbaseTX] = require("./transaction")
import rocksdb from 'rocksdb'
import fs from 'fs'
import {NewCoinbaseTX} from './transaction.js'
import Block from "./block.js";
const dbFile = "blockchain.db"
let dbIsOpen = false;
let db = rocksdb(dbFile);
class DB {
static dbExists() {
return fs.existsSync(dbFile);
}
static async open() {
if (dbIsOpen) {
return
}
await new Promise((resolve, reject) => {
db.open((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
dbIsOpen = true;
}
static async get(key) {
if (dbIsOpen === false) {
await DB.open();
}
return await new Promise((resolve, reject) => {
db.get(key, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data);
}
});
});
}
static async put(key, value) {
if (dbIsOpen === false) {
await DB.open();
}
await new Promise((resolve, reject) => {
db.put(key, value, (err) => {
if (err)
reject(err);
else {
resolve();
}
});
});
}
}
class Blockchain {
constructor(tip) {
this.tip = tip;
}
async mineBlock(txs) {
let lastHash = await DB.get("l")
let lastBlockData = await DB.get(lastHash);
let lastBlock = JSON.parse(lastBlockData);
let newBlock = Block.newBlock(lastBlock.index+1, new Date().getTime()/1000, txs, lastBlock.hash);
await DB.put(newBlock.hash, JSON.stringify(newBlock));
await DB.put("l", newBlock.hash);
console.log(`add new block, index: ${newBlock.index}, hash: ${lastBlock.hash}`);
}
async findUnspentTransactions(address) {
let unspentTXs = []
let spentTXOs = new Map();
let it = this.iterator();
while (true) {
let block = await it.next();
for (const tx of block.transactions) {
let txID = tx. id;
Outputs:
for (let i = 0; i < tx.vout.length; i++) {
if (spentTXOs[txID] !== undefined) {
for (const spendOut of spentTXOs[txID]) {
if (spendOut === i) {
console.log("this output has been used")
continue Outputs
}
}
}
let out = tx.vout[i];
if (out.canBeUnlockedWith(address)) {
unspentTXs.push(tx);
}
}
if (tx.isCoinbase() === false) {
for (const vin of tx.vin) {
if (vin.canUnlockOutputWith(address)) {
if (!spentTXOs.has(vin.txid)) {
spentTXOs[vin.txid] = [];
}
spentTXOs[vin.txid].push(vin.vout);
}
}
}
}
if (block.preBlockHash.length === 0) {
break;
}
}
return unspentTXs;
}
async findSpendableOutputs(address, amount) {
let unspentOutputs = new Map();
let unspentTXs = await this.findUnspentTransactions(address);
let accumulate = 0;
work:
for (const tx of unspentTXs) {
for (let i = 0; i < tx.vout.length; i++) {
let out = tx.vout[i];
if (out.canBeUnlockedWith(address) && accumulate < amount) {
accumulate += out.value;
if (!unspentOutputs.has(tx.id)) {
unspentOutputs.set(tx.id, []);
}
unspentOutputs.get(tx.id).push(i);
}
if (accumulate >= amount) {
break work;
}
}
}
return {accumulate: accumulate, unspentOutputs: unspentOutputs};
}
async findUTXO(address) {
let UTXOs = []
let unspentTransactions = await this.findUnspentTransactions(address);
for (const tx of unspentTransactions) {
for (const out of tx.vout) {
if (out.canBeUnlockedWith(address)) {
UTXOs.push(out);
}
}
}
return UTXOs;
}
static async newBlockchain(address) {
if (DB.dbExists() === false) {
console.log("Db not exist");
process.exit(1);
}
let tip = await DB.get("l");
return new Blockchain(tip);
}
static async createBlockchain(address) {
if (DB.dbExists()) {
console.log("Blockchain exists");
return;
}
//create genesis block
let cbtx = NewCoinbaseTX(address, "");
let genesis = Block.newGenesisBlock(cbtx);
await DB.put(genesis.hash, JSON.stringify(genesis));
await DB.put("l", genesis.hash);
return new Blockchain(genesis.hash);
}
iterator() {
return new BlockchainIterator(this.tip, this.db);
}
}
class BlockchainIterator {
constructor(hash, db) {
this.currentHash = hash;
this.db = db;
}
async next() {
let block = Block.fromJson(await DB.get(this.currentHash));
this.currentHash = block.preBlockHash;
return block
}
}
// module.exports = Blockchain;
export default Blockchain