-
Notifications
You must be signed in to change notification settings - Fork 96
/
inputs.js
302 lines (282 loc) · 11.2 KB
/
inputs.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*jslint node: true */
"use strict";
var async = require('async');
var objectHash = require("./object_hash.js");
var constants = require("./constants.js");
var paid_witnessing = require("./paid_witnessing.js");
var headers_commission = require("./headers_commission.js");
var mc_outputs = require("./mc_outputs.js");
const storage = require("./storage.js");
var TRANSFER_INPUT_SIZE = 0 // type: "transfer" omitted
+ 44 // unit
+ 8 // message_index
+ 8; // output_index
var TRANSFER_INPUT_KEYS_SIZE = "unit".length + "message_index".length + "output_index".length;
var HEADERS_COMMISSION_INPUT_SIZE = 18 // type: "headers_commission"
+ 8 // from_main_chain_index
+ 8; // to_main_chain_index
var HEADERS_COMMISSION_INPUT_KEYS_SIZE = "type".length + "from_main_chain_index".length + "to_main_chain_index".length;
var WITNESSING_INPUT_SIZE = 10 // type: "witnessing"
+ 8 // from_main_chain_index
+ 8; // to_main_chain_index
var WITNESSING_INPUT_KEYS_SIZE = "type".length + "from_main_chain_index".length + "to_main_chain_index".length;
var ADDRESS_SIZE = 32;
var ADDRESS_KEY_SIZE = "address".length;
// bMultiAuthored includes all addresses, not just those that pay
// arrAddresses is paying addresses
// spend_unconfirmed is one of: none, all, own
function pickDivisibleCoinsForAmount(conn, objAsset, arrAddresses, last_ball_mci, amount, size, paid_temp_data_fee, bMultiAuthored, spend_unconfirmed, onDone) {
function getOversizeFee(s) {
return (last_ball_mci >= constants.v4UpgradeMci && !objAsset) ? storage.getOversizeFee(s - paid_temp_data_fee, last_ball_mci) : 0;
}
if (!objAsset && !size)
throw Error(`no size for base pickDivisibleCoinsForAmount`);
var asset = objAsset ? objAsset.asset : null;
console.log("pick coins in "+asset+" for amount "+amount+" with spend_unconfirmed "+spend_unconfirmed);
var is_base = objAsset ? 0 : 1;
var bWithKeys = (last_ball_mci >= constants.includeKeySizesUpgradeMci);
var transfer_input_size = is_base ? (TRANSFER_INPUT_SIZE + (bWithKeys ? TRANSFER_INPUT_KEYS_SIZE : 0)) : 0;
var arrInputsWithProofs = [];
var total_amount = 0;
var required_amount = amount;
let net_required_amount = required_amount - getOversizeFee(size);
if (!(typeof last_ball_mci === 'number' && last_ball_mci >= 0))
throw Error("invalid last_ball_mci: "+last_ball_mci);
var confirmation_condition;
if (spend_unconfirmed === 'none')
confirmation_condition = 'AND main_chain_index<='+last_ball_mci;
else if (spend_unconfirmed === 'all')
confirmation_condition = '';
else if (spend_unconfirmed === 'own')
confirmation_condition = 'AND ( main_chain_index<='+last_ball_mci+' OR EXISTS ( \n\
SELECT 1 FROM unit_authors CROSS JOIN my_addresses USING(address) WHERE unit_authors.unit=outputs.unit \n\
UNION \n\
SELECT 1 FROM unit_authors CROSS JOIN shared_addresses ON address=shared_address WHERE unit_authors.unit=outputs.unit \n\
UNION \n\
SELECT 1 FROM unit_authors WHERE unit_authors.unit=outputs.unit AND unit_authors.address IN(' + arrAddresses.map(conn.escape).join(', ') + ')\n\
) )';
else
throw Error("invalid spend_unconfirmed="+spend_unconfirmed);
// adds element to arrInputsWithProofs
function addInput(input){
total_amount += input.amount;
var objInputWithProof = {input: input};
if (objAsset && objAsset.is_private){ // for type=payment only
var spend_proof = objectHash.getBase64Hash({
asset: asset,
amount: input.amount,
address: input.address,
unit: input.unit,
message_index: input.message_index,
output_index: input.output_index,
blinding: input.blinding
});
var objSpendProof = {spend_proof: spend_proof};
if (bMultiAuthored)
objSpendProof.address = input.address;
objInputWithProof.spend_proof = objSpendProof;
}
if (!bMultiAuthored || !input.type)
delete input.address;
delete input.amount;
delete input.blinding;
arrInputsWithProofs.push(objInputWithProof);
}
// first, try to find a coin just bigger than the required amount
function pickOneCoinJustBiggerAndContinue(){
if (amount === Infinity)
return pickMultipleCoinsAndContinue();
var more = is_base ? '>' : '>=';
conn.query(
"SELECT unit, message_index, output_index, amount, blinding, address \n\
FROM outputs \n\
CROSS JOIN units USING(unit) \n\
WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\
AND sequence='good' "+confirmation_condition+" \n\
ORDER BY is_stable DESC, amount LIMIT 1",
[arrSpendableAddresses, net_required_amount + transfer_input_size + getOversizeFee(size + transfer_input_size)],
function(rows){
if (rows.length === 1){
var input = rows[0];
// default type is "transfer"
addInput(input);
onDone(arrInputsWithProofs, total_amount);
}
else
pickMultipleCoinsAndContinue();
}
);
}
// then, try to add smaller coins until we accumulate the target amount
function pickMultipleCoinsAndContinue(){
conn.query(
"SELECT unit, message_index, output_index, amount, address, blinding \n\
FROM outputs \n\
CROSS JOIN units USING(unit) \n\
WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\
AND sequence='good' "+confirmation_condition+" \n\
ORDER BY amount DESC LIMIT ?",
[arrSpendableAddresses, constants.MAX_INPUTS_PER_PAYMENT_MESSAGE-2],
function(rows){
async.eachSeries(
rows,
function(row, cb){
var input = row;
objectHash.cleanNulls(input);
net_required_amount += transfer_input_size;
size += transfer_input_size;
required_amount = net_required_amount + getOversizeFee(size);
addInput(input);
// if we allow equality, we might get 0 amount for change which is invalid
var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount);
bFound ? cb('found') : cb();
},
function(err){
if (err === 'found')
onDone(arrInputsWithProofs, total_amount);
else if (asset)
issueAsset();
else
addHeadersCommissionInputs();
}
);
}
);
}
function addHeadersCommissionInputs(){
addMcInputs("headers_commission", HEADERS_COMMISSION_INPUT_SIZE + (bWithKeys ? HEADERS_COMMISSION_INPUT_KEYS_SIZE : 0),
headers_commission.getMaxSpendableMciForLastBallMci(last_ball_mci), addWitnessingInputs);
}
function addWitnessingInputs(){
addMcInputs("witnessing", WITNESSING_INPUT_SIZE + (bWithKeys ? WITNESSING_INPUT_KEYS_SIZE : 0), paid_witnessing.getMaxSpendableMciForLastBallMci(last_ball_mci), issueAsset);
}
function addMcInputs(type, input_size, max_mci, onStillNotEnough){
var address_size = ADDRESS_SIZE + (bWithKeys ? ADDRESS_KEY_SIZE : 0);
var full_input_size = input_size + (bMultiAuthored ? address_size : 0);
async.eachSeries(
arrAddresses,
function(address, cb){
var target_amount = net_required_amount - total_amount + full_input_size + getOversizeFee(size + full_input_size);
mc_outputs.findMcIndexIntervalToTargetAmount(conn, type, address, max_mci, target_amount, {
ifNothing: cb,
ifFound: function(from_mc_index, to_mc_index, earnings, bSufficient){
if (earnings === 0)
throw Error("earnings === 0");
if (earnings <= full_input_size) // skip net negative MC inputs
return cb();
var input = {
type: type,
from_main_chain_index: from_mc_index,
to_main_chain_index: to_mc_index
};
if (bMultiAuthored)
input.address = address;
arrInputsWithProofs.push({input: input});
total_amount += earnings;
net_required_amount += full_input_size;
size += full_input_size;
required_amount = net_required_amount + getOversizeFee(size);
(total_amount > required_amount)
? cb("found") // break eachSeries
: cb(); // try next address
}
});
},
function(err){
if (!err)
console.log(arrAddresses+" "+type+": got only "+total_amount+" out of required "+required_amount);
(err === "found") ? onDone(arrInputsWithProofs, total_amount) : onStillNotEnough();
}
);
}
function issueAsset(){
if (!asset)
return finish();
else{
if (amount === Infinity && !objAsset.cap) // don't try to create infinite issue
return onDone(null);
}
console.log("will try to issue asset "+asset);
// for issue, we use full list of addresses rather than spendable addresses
if (objAsset.issued_by_definer_only && arrAddresses.indexOf(objAsset.definer_address) === -1)
return finish();
var issuer_address = objAsset.issued_by_definer_only ? objAsset.definer_address : arrAddresses[0];
var issue_amount = objAsset.cap || (required_amount - total_amount) || 1; // 1 currency unit in case required_amount = total_amount
function addIssueInput(serial_number){
total_amount += issue_amount;
var input = {
type: "issue",
amount: issue_amount,
serial_number: serial_number
};
if (bMultiAuthored)
input.address = issuer_address;
var objInputWithProof = {input: input};
if (objAsset && objAsset.is_private){
var spend_proof = objectHash.getBase64Hash({
asset: asset,
amount: issue_amount,
denomination: 1,
address: issuer_address,
serial_number: serial_number
});
var objSpendProof = {spend_proof: spend_proof};
if (bMultiAuthored)
objSpendProof.address = input.address;
objInputWithProof.spend_proof = objSpendProof;
}
arrInputsWithProofs.unshift(objInputWithProof);
var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount);
bFound ? onDone(arrInputsWithProofs, total_amount) : finish();
}
if (objAsset.cap){
conn.query("SELECT 1 FROM inputs WHERE type='issue' AND asset=?", [asset], function(rows){
if (rows.length > 0) // already issued
return finish();
addIssueInput(1);
});
}
else{
conn.query(
"SELECT MAX(serial_number) AS max_serial_number FROM inputs WHERE type='issue' AND asset=? AND address=?",
[asset, issuer_address],
function(rows){
var max_serial_number = (rows.length === 0) ? 0 : rows[0].max_serial_number;
addIssueInput(max_serial_number+1);
}
);
}
}
function finish(){
if (amount === Infinity && arrInputsWithProofs.length > 0)
onDone(arrInputsWithProofs, total_amount);
else
onDone(null);
}
var arrSpendableAddresses = arrAddresses.concat(); // cloning
if (objAsset && objAsset.auto_destroy){
var i = arrAddresses.indexOf(objAsset.definer_address);
if (i>=0)
arrSpendableAddresses.splice(i, 1);
}
if (arrSpendableAddresses.length > 0)
pickOneCoinJustBiggerAndContinue();
else
issueAsset();
}
function getConfirmationConditionSql(spend_unconfirmed){
if (spend_unconfirmed === 'none')
return 'AND is_stable=1';
else if (spend_unconfirmed === 'all')
return '';
else if (spend_unconfirmed === 'own')
return 'AND ( is_stable=1 OR EXISTS ( \n\
SELECT 1 FROM unit_authors CROSS JOIN my_addresses USING(address) WHERE unit_authors.unit=outputs.unit \n\
UNION \n\
SELECT 1 FROM unit_authors CROSS JOIN shared_addresses ON address=shared_address WHERE unit_authors.unit=outputs.unit \n\
) )';
else
throw Error("invalid spend_unconfirmed="+spend_unconfirmed);
}
exports.pickDivisibleCoinsForAmount = pickDivisibleCoinsForAmount;
exports.getConfirmationConditionSql = getConfirmationConditionSql;