-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.js
216 lines (183 loc) · 6.99 KB
/
listener.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
import fs from 'fs';
import ethers from 'ethers';
import BitcoinHelpers from '@keep-network/tbtc.js/src/BitcoinHelpers.js';
import EthereumHelpers from '@keep-network/tbtc.js/src/EthereumHelpers.js';
import TBTCSystem from "@keep-network/tbtc/artifacts/TBTCSystem.json";
import TBTCDepositToken from "@keep-network/tbtc/artifacts/TBTCDepositToken.json";
import Deposit from "@keep-network/tbtc/artifacts/Deposit.json";
import BondedECDSAKeep from "@keep-network/keep-ecdsa/artifacts/BondedECDSAKeep.json";
import DepositLog from "@keep-network/tbtc/artifacts/DepositLog.json";
if (process.argv.length < 3 || !process.argv[2]) {
console.error('node listener.js [password]');
process.exit(1);
}
let wallet;
let ip = new ethers.providers.InfuraProvider('homestead', process.env.INFURA_API);
const j = fs.readFileSync('wallet.json', 'utf8');
ethers.Wallet.fromEncryptedJson(j, process.argv[2]).then((w) => {
wallet = w.connect(ip);
});
const tbtcSysContract = new ethers.Contract(TBTCSystem.networks["1"].address, TBTCSystem.abi, ip);
const states = [
"START",
"AWAITING_SIGNER_SETUP",
"AWAITING_BTC_FUNDING_PROOF",
"FAILED_SETUP",
"ACTIVE", // includes courtesy call
"AWAITING_WITHDRAWAL_SIGNATURE",
"AWAITING_WITHDRAWAL_PROOF",
"REDEEMED",
"COURTESY_CALL",
"FRAUD_LIQUIDATION_IN_PROGRESS",
"LIQUIDATION_IN_PROGRESS",
"LIQUIDATED"
];
const fourHours = ethers.BigNumber.from((60 / 15) * 60 * 4) // ~4hours in blocks
const fiveMinutes = ethers.BigNumber.from((60 / 15) * 5) // ~5minutes in blocks
const redemptionProofTimeout = ethers.BigNumber.from(6 * 60 * 60); // 6 hours
async function filterDeposits(ev) {
const [ dAddr, digest, r, s, ts ] = ev.args;
const d = new ethers.Contract(dAddr, Deposit.abi, ip);
const state = states[await d.currentState()];
return state === 'AWAITING_WITHDRAWAL_PROOF';
}
async function broadcastSignedTx(rr, r, s) {
const [ dAddr, requester, dgest, utxoValue, redeemerOutputScript, requestedFee, outpoint] = rr.args;
const expectedValue = utxoValue.sub(requestedFee).toNumber();
const d = new ethers.Contract(dAddr, Deposit.abi, ip);
const unsignedTransaction = BitcoinHelpers.Transaction.constructOneInputOneOutputWitnessTransaction(
outpoint.replace("0x", ""),
0,
expectedValue,
EthereumHelpers.bytesToRaw(redeemerOutputScript)
);
const depositPks = await tbtcSysContract.queryFilter(tbtcSysContract.filters.RegisteredPubkey(d.address));
const pk = depositPks[depositPks.length - 1].args;
// 0. depositAddr, 1. X, 2. Y, 3. timestamp
const signedTransaction = BitcoinHelpers.Transaction.addWitnessSignature(
unsignedTransaction,
0,
r.replace("0x", ""),
s.replace("0x", ""),
BitcoinHelpers.publicKeyPointToPublicKeyString(
pk[1],
pk[2]
)
);
while (true) {
try {
console.log(`broadcasting signedTransaction: ${signedTransaction}`);
const bTx = await BitcoinHelpers.Transaction.broadcast(signedTransaction);
return bTx.transactionID;
break;
} catch (err) {
console.error(err.message);
}
}
}
async function extracFromRedemptionSig(ev) {
const [ dAddr, digest, r, s, ts ] = ev;
const rr = await tbtcSysContract.queryFilter(tbtcSysContract.filters.RedemptionRequested(null, null, digest))
if (rr.length < 1) {
console.log(`could not find redemption request for digest ${digest}`);
return {};
}
const blockNumber = await ip.getBlockNumber();
const out = {
dAddr: dAddr,
deadline: ts.add(redemptionProofTimeout),
blockNum: ethers.BigNumber.from(blockNumber),
blockTarget: ethers.BigNumber.from(blockNumber).add(fourHours),
}
console.log(`broadcast the bitcoin tx just in case`);
out.transactionID = await broadcastSignedTx(rr[0], r, s);
return out;
}
// bts is blockNum => Deposits[]
function addTarget(bts, tb, d) {
if (bts.has(tb)) {
bts.set(tb, bts.get(tb).concat([d]))
} else {
bts.set(tb, [d])
}
}
const asyncFilter = async (arr, predicate) =>
arr.reduce(async (memo, e) =>
await predicate(e) ? [...await memo, e] : memo
, []);
BitcoinHelpers.setElectrumConfig({
server: "electrumx-server.tbtc.network",
port: 8443,
protocol: "wss"
});
async function main() {
try {
const blockTargets = new Map() // blocknum => [deposits]
ip.on("block", async (blockNum) => {
blockNum = blockNum.toString()
const numTargets = blockTargets.get(blockNum) ? blockTargets.get(blockNum).length : 0;
console.log(`[ #${blockNum.toString()} ] has ${numTargets} targets`)
if (blockTargets.has(blockNum)) {
for (let ds of blockTargets.get(blockNum)) {
const d = new ethers.Contract(ds.dAddr, Deposit.abi, wallet);
const depositState = states[await d.currentState()];
if (depositState === 'AWAITING_WITHDRAWAL_PROOF') { // Proof was not submitted. We should do it >:[
BitcoinHelpers.Transaction.waitForConfirmations(
ds.transactionID,
6,
({transactionID, confirmations, requiredConfirmations}) => {
console.log(`got ${confirmations} of ${requiredConfirmations} confirmations for ${ds.transactionID}`);
}
).then(async (conf) => {
console.log(`got ${conf} for ${ds.transactionID}`);
const {
parsedTransaction,
merkleProof,
chainHeaders,
txInBlockIndex
} = await BitcoinHelpers.Transaction.getSPVProof(ds.transactionID, 6);
const { version, txInVector, txOutVector, locktime } = parsedTransaction;
console.log(`calling provideRedemptionProof()`);
const proofTx = await d.provideRedemptionProof(
Buffer.from(version, "hex"),
Buffer.from(txInVector, "hex"),
Buffer.from(txOutVector, "hex"),
Buffer.from(locktime, "hex"),
Buffer.from(merkleProof, "hex"),
txInBlockIndex,
Buffer.from(chainHeaders, "hex")
);
await proofTx.wait();
})
} else {
console.log(`deposit ${ds.dAddr} was redeemed properly`)
}
}
}
})
// Check for pending redemption requests that we might want to pick up.
const redemptionSigs = await tbtcSysContract.queryFilter(tbtcSysContract.filters.GotRedemptionSignature());
const waiting = await asyncFilter(redemptionSigs, filterDeposits);
console.log(`have ${ waiting.length } deposits waiting for the withdrawal proof; adding listeners`);
let sigsWithDeadlines = [];
for (let w of waiting) {
sigsWithDeadlines.push(await extracFromRedemptionSig(w.args));
}
for (let i in sigsWithDeadlines) {
const target = ethers.BigNumber.from(waiting[i].blockNumber).add(fourHours).toString();
console.log(`${sigsWithDeadlines[i].dAddr} adding listener for #${ target }`);
addTarget(blockTargets, target, sigsWithDeadlines[i])
}
console.log(`Listening for GotRedemptionSignature`)
tbtcSysContract.on(tbtcSysContract.filters.GotRedemptionSignature(), async (...ev) => {
let sig = await extracFromRedemptionSig(ev);
console.log(`${sig.dAddr} adding listener for #${ sig.blockTarget.toString() }`);
addTarget(blockTargets, sig.blockTarget.toString(), sig)
});
} catch(err) {
console.error(`Could not authorize: ${err}`)
console.error(err);
process.exit(1);
}
}
main().catch(err => { console.error(err); })