/
logic.js
406 lines (355 loc) · 13.4 KB
/
logic.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
This file is part of kaya.
Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd.
kaya is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
kaya is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
kaya. If not, see <http://www.gnu.org/licenses/>.
*/
// logic.js : Logic Script
const hashjs = require('hash.js');
const fs = require('fs');
const { Zilliqa } = require('zilliqa-js');
const LOG_LOGIC = require('debug')('kaya:logic');
const scillaCtrl = require('./components/scilla/scilla');
const walletCtrl = require('./components/wallet/wallet');
const blockchain = require('./components/blockchain');
const config = require('./config');
// non-persistent states. Initializes whenever server starts
let transactions = {};
const createdContractsByUsers = {}; // address => contract addresses
/* Dummy constructor for zilliqajs */
// @dev: Will be replaced once zilliqa-js exposes utils without constructors
const zilliqa = new Zilliqa({
nodeUrl: 'http://localhost:8888',
});
/* Utility functions */
function pad(number, length) {
let str = number.toString();
while (str.length < length) {
str = `0${str}`;
}
return str;
}
Date.prototype.YYYYMMDDHHMMSS = () => {
const yyyy = this.getFullYear().toString();
const MM = pad(this.getMonth() + 1, 2);
const dd = pad(this.getDate(), 2);
const hh = pad(this.getHours(), 2);
const mm = pad(this.getMinutes(), 2);
const ss = pad(this.getSeconds(), 2);
return yyyy + MM + dd + hh + mm + ss;
};
// check multiplication overflow: Returns true if overflow
const checkOverflow = (a, b) => {
const c = a * b;
return a !== c / b || b !== c / a;
};
// compute contract address from the sender's current nonce
const computeContractAddr = (sender) => {
const userNonce = walletCtrl.getBalance(sender).nonce;
const nonceStr = zilliqa.util.intToByteArray(userNonce, 64).join('');
const digest = hashjs.sha256().update(sender).update(nonceStr).digest('hex');
return digest.slice(24);
};
// compute transactionHash from the payload
const computeTransactionHash = (payload) => {
// transactionID is a sha256 digest of txndetails
const copyPayload = JSON.parse(JSON.stringify(payload));
delete copyPayload.signature; // txn hash does not include signature
const buf = Buffer.from(JSON.stringify(copyPayload));
const transactionHash = hashjs
.sha256()
.update(buf)
.digest('hex');
return transactionHash;
};
// check for common elements within the list
const intersect = (a, b) => [...new Set(a)].filter(x => new Set(b).has(x));
// checks if the transactionJson is well-formed
const checkTransactionJson = (data) => {
if (data !== null && typeof data !== 'object') return false;
const payload = data[0];
const expectedFields = [
'version',
'nonce',
'to',
'amount',
'pubKey',
'gasPrice',
'gasLimit',
'signature',
];
/* Checking the keys in the payload */
const numKeys = Object.keys(payload).length;
if (numKeys < 8) return false;
const payloadKeys = Object.keys(payload);
const expected = intersect(payloadKeys, expectedFields).length;
const actual = Object.keys(expectedFields).length;
// number of overlap keys must be the same as the expected keys
if (expected !== actual) return false;
// validate signature - TODO
return true;
};
module.exports = {
processCreateTxn: async (data, saveMode) => {
LOG_LOGIC('Processing transaction...');
// todo: check for well-formness of the payload data
LOG_LOGIC(`Payload well-formed? ${checkTransactionJson(data)}`);
if (!checkTransactionJson(data)) {
throw new Error('Invalid Tx Json');
}
const currentBNum = blockchain.getBlockNum();
let dir = 'tmp/';
if (saveMode) {
console.log('Save mode enabled.');
dir = 'data/';
}
const payload = data[0];
const senderAddress = zilliqa.util.getAddressFromPublicKey(payload.pubKey);
LOG_LOGIC(`Sender: ${senderAddress}`);
const userNonce = walletCtrl.getBalance(senderAddress).nonce;
LOG_LOGIC(`User Nonce: ${userNonce}`);
LOG_LOGIC(`Payload Nonce: ${payload.nonce}`);
// check if payload gasPrice is sufficient
const blockchainGasPrice = config.blockchain.gasPrice;
if (payload.gasPrice < blockchainGasPrice) {
throw new Error(
`Payload gas price is insufficient. Current gas price is ${
config.blockchain.gasPrice
}`,
);
}
// check if the payload.nonce is valid
if (payload.nonce === userNonce + 1) {
// p2p token transfer
if (!payload.code && !payload.data) {
LOG_LOGIC('p2p token tranfer');
walletCtrl.deductFunds(
senderAddress,
payload.amount + payload.gasLimit,
);
walletCtrl.increaseNonce(senderAddress);
walletCtrl.addFunds(payload.to, payload.amount);
} else {
/* contract generation */
LOG_LOGIC('Task: Contract Deployment / Create Transaction');
// take the sha256 hash of address+nonce, then extract the rightmost 20 bytes
const contractAddr = computeContractAddr(senderAddress);
if (checkOverflow(payload.gasLimit, payload.gasPrice)) {
throw new Error('Overflow detected: Invalid gas limit or gas price');
}
const gasLimitToZil = payload.gasLimit * payload.gasPrice;
const gasAndAmount = payload.amount + gasLimitToZil;
if (!walletCtrl.sufficientFunds(senderAddress, gasAndAmount)) {
LOG_LOGIC('Insufficient funds. Returning error to client.');
throw new Error('Insufficient funds');
}
LOG_LOGIC(`Contract will be deployed at: ${contractAddr}`);
const responseData = await scillaCtrl.executeScillaRun(
payload,
contractAddr,
dir,
currentBNum,
payload.gasLimit,
);
// Deduct funds
const nextAddr = responseData.nextAddress;
const gasConsumed = payload.gasLimit - responseData.gasRemaining;
if (checkOverflow(gasConsumed, payload.gasPrice)) {
throw new Error('Overflow detected: Invalid gas limit or gas price');
}
const gasConsumedInZil = gasConsumed * payload.gasPrice;
walletCtrl.deductFunds(
senderAddress,
payload.amount + gasConsumedInZil,
);
walletCtrl.increaseNonce(senderAddress); // only increase if a contract is successful
if (nextAddr !== '0'.repeat(40) && nextAddr.substring(2) !== senderAddress) {
console.log('Multi-contract calls not supported.');
throw new Error('Multi-contract calls are not supported yet.');
}
// Only update if it is a deployment call
if (payload.code && payload.to === '0'.repeat(40)) {
// Update address_to_contracts
if (senderAddress in createdContractsByUsers) {
LOG_LOGIC('User has contracts. Appending to list');
createdContractsByUsers[senderAddress].push(contractAddr);
} else {
LOG_LOGIC('No existing contracts. Creating new entry.');
createdContractsByUsers[senderAddress] = [contractAddr];
}
LOG_LOGIC('Addr-to-Contracts: %O', createdContractsByUsers);
}
}
} else {
// payload.nonce is not valid. Deduct gas anyway
// FIX ME: Waiting for scilla interpreter to return a structured output
// about out of gas errors
// https://github.com/Zilliqa/scilla/issues/214
walletCtrl.deductFunds(senderAddress, payload.gasLimit);
LOG_LOGIC('Invalid Nonce');
throw new Error('Invalid Tx Json');
}
/* Update Transactions */
const txnId = computeTransactionHash(payload);
LOG_LOGIC(`Transaction will be logged as ${txnId}`);
const txnDetails = {
ID: txnId,
amount: payload.amount,
nonce: payload.nonce,
senderPubKey: payload.pubKey,
signature: payload.signature,
toAddr: payload.to,
version: payload.version,
};
transactions[txnId] = txnDetails;
return txnId;
},
bootstrapFile: (filepath) => {
// bootstraps state of transactions and caddr owner
const data = JSON.parse(fs.readFileSync(filepath, 'utf-8'));
LOG_LOGIC('State of blockchain:');
transactions = data.transactions;
LOG_LOGIC(transactions);
},
processGetTransaction: (data) => {
if (!data) {
LOG_LOGIC('Invalid params');
const err = new Error(
'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised',
);
throw err;
}
LOG_LOGIC(`TxnID: ${data[0]}`);
const res = transactions[data[0]];
if (res) {
return res;
}
throw new Error('Txn Hash not Present.');
},
processGetRecentTransactions: () => {
LOG_LOGIC('Getting Recent Transactions');
const txnhashes = Object.keys(transactions);
const responseObj = {};
responseObj.TxnHashes = txnhashes.reverse();
responseObj.number = txnhashes.length;
return responseObj;
},
processGetSmartContractInit: (data, saveMode) => {
LOG_LOGIC('Getting SmartContract Init');
if (!data) {
LOG_LOGIC('Invalid params');
const err = new Error(
'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised',
);
throw err;
}
const contractAddress = data[0];
if (contractAddress == null || !zilliqa.util.isAddress(contractAddress)) {
console.log('Invalid request');
throw new Error('Address size inappropriate');
}
const dir = saveMode ? 'data/' : 'tmp/';
const initFile = `${dir}${contractAddress.toLowerCase()}_init.json`;
if (!fs.existsSync(initFile)) {
console.log(`No init file found (Contract: ${contractAddress}`);
throw new Error('Address does not exist');
}
const retMsg = JSON.parse(fs.readFileSync(initFile, 'utf-8'));
return retMsg;
},
processGetSmartContractCode: (data, saveMode) => {
LOG_LOGIC('Getting SmartContract code');
if (!data) {
LOG_LOGIC('Invalid params');
const err = new Error(
'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised',
);
throw err;
}
const contractAddress = data[0];
if (contractAddress == null || !zilliqa.util.isAddress(contractAddress)) {
console.log('Invalid request');
throw new Error('Address size inappropriate');
}
const dir = saveMode ? 'data/' : 'tmp/';
const codePath = `${dir}${contractAddress.toLowerCase()}_code.scilla`;
if (!fs.existsSync(codePath)) {
console.log(`No code file found (Contract: ${contractAddress}`);
throw new Error('Address does not exist');
}
LOG_LOGIC('Returning smart contract code to caller.');
const res = {};
res.code = fs.readFileSync(codePath, 'utf-8');
return res;
},
processGetSmartContractState: (data, saveMode) => {
LOG_LOGIC('Getting SmartContract State');
if (!data) {
LOG_LOGIC('Invalid params');
const err = new Error(
'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised',
);
throw err;
}
const contractAddress = data[0];
if (contractAddress == null || !zilliqa.util.isAddress(contractAddress)) {
console.log('Invalid request');
throw new Error('Address size inappropriate');
}
const dir = saveMode ? 'data/' : 'tmp/';
const statePath = `${dir}${contractAddress.toLowerCase()}_state.json`;
if (!fs.existsSync(statePath)) {
console.log(`No state file found (Contract: ${contractAddress}`);
throw new Error('Address does not exist');
}
const retMsg = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
LOG_LOGIC(retMsg);
return retMsg;
},
/*
getSmartContracts: Returns the list of smart contracts created by an account
*/
processGetSmartContracts: (data, saveMode) => {
if (!data) {
LOG_LOGIC('Invalid params');
const err = new Error(
'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised',
);
throw err;
}
const addr = data[0];
console.log(`Getting smart contracts created by ${addr}`);
if (addr == null || !zilliqa.util.isAddress(addr)) {
console.log('Invalid request');
throw new Error('Address size inappropriate');
}
const stateLists = [];
if (!createdContractsByUsers[addr]) {
throw new Error('Address does not exist');
}
// Addr found - proceed to append state to return list
const dir = saveMode ? 'data/' : 'tmp/';
const contracts = createdContractsByUsers[addr];
console.log(contracts);
contracts.forEach((contractId) => {
const statePath = `${dir}${contractId.toLowerCase()}_state.json`;
if (!fs.existsSync(statePath)) {
console.log(`No state file found (Contract: ${contractId}`);
throw new Error('Address does not exist');
}
const retMsg = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
const contractStateObj = {};
contractStateObj.address = contractId;
contractStateObj.state = retMsg;
stateLists.push(contractStateObj);
});
return stateLists;
},
};