-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbitcoinscript-interpreter.ts
More file actions
75 lines (60 loc) · 1.77 KB
/
bitcoinscript-interpreter.ts
File metadata and controls
75 lines (60 loc) · 1.77 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
import * as crypto from "crypto";
import { ec as EC } from "elliptic";
const ec = new EC("secp256k1");
export function sha256(data: Buffer): Buffer {
return crypto.createHash("sha256").update(data).digest();
}
export function hash160(data: Buffer): Buffer {
return ripemd160(sha256(data));
}
function ripemd160(data: Buffer): Buffer {
return crypto.createHash("ripemd160").update(data).digest();
}
export enum OpCode {
OP_DUP,
OP_HASH160,
OP_EQUALVERIFY,
OP_CHECKSIG,
OP_EQUAL,
}
export type OpCodeFunction = (stack: Buffer[]) => void;
export const opCodeFunctions: { [key in OpCode]: OpCodeFunction } = {
[OpCode.OP_DUP]: (stack) => {},
[OpCode.OP_HASH160]: (stack) => {},
[OpCode.OP_EQUALVERIFY]: (stack) => {},
[OpCode.OP_CHECKSIG]: (stack) => {},
[OpCode.OP_EQUAL]: (stack) => {},
};
export class BitcoinScriptInterpreter {
private stack: Buffer[];
constructor() {
this.stack = [];
}
private push(data: Buffer): void {
this.stack.push(data);
}
executeScript(script: (OpCode | Buffer)[]): boolean {
for (const item of script) {
if (typeof item === "number") {
const opFunc = opCodeFunctions[item as OpCode];
if (!opFunc) throw new Error("Invalid OpCode");
opFunc(this.stack);
} else if (Buffer.isBuffer(item)) {
this.push(item);
} else {
throw new Error("Invalid script element");
}
}
const result = this.stack.pop();
if (!result || result.length !== 1) {
throw new Error("Invalid script result");
}
return result[0] === 1;
}
static serializeScript(script: (OpCode | Buffer)[]): Buffer {
throw new Error("Implement me!!");
}
static deserializeScript(script: (OpCode | Buffer)[]): (OpCode | Buffer)[] {
throw new Error("Implement me!!");
}
}