-
Notifications
You must be signed in to change notification settings - Fork 402
/
burrow.js
243 lines (215 loc) · 8.23 KB
/
burrow.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
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const fs = require('fs');
const monax = require('@monax/burrow');
const { BlockchainInterface, CaliperUtils, TxStatus } = require('@hyperledger/caliper-core');
const logger = CaliperUtils.getLogger('burrow.js');
/**
Read the connection details from the config file.
@param {object} config Adapter config.
@param {string} workspace_root The absolute path to the root location for the configuration files.
@return {object} url, account Connection settings.
*/
function burrowConnect(config, workspace_root) {
let host = config.burrow.network.validator.host;
if (host === null) {
throw new Error('host url not set');
}
let port = config.burrow.network.validator.port;
if (port === null) {
throw new Error('grpc port not set');
}
let account;
try {
account = fs.readFileSync(CaliperUtils.resolvePath(config.burrow.network.validator.address, workspace_root)).toString();
} catch (err) {
account = config.burrow.network.validator.address.toString();
}
logger.info(`Account: ${account}`);
if (account === null) {
throw new Error('no validator account found');
}
return {
url: host + ':' + port,
account: account,
};
}
/**
* Implements {BlockchainInterface} for a Burrow backend.
*/
class Burrow extends BlockchainInterface {
/**
* Create a new instance of the {Burrow} class.
* @param {string} config_path The path of the Burrow network configuration file.
* @param {string} workspace_root The absolute path to the root location for the application configuration files.
*/
constructor(config_path, workspace_root) {
super(config_path);
this.statusInterval = null;
this.bcType = 'burrow';
this.workspaceRoot = workspace_root;
}
/**
* Initialize the {Burrow} object.
* @return {time} sleep
*/
init() {
return CaliperUtils.sleep(2000);
}
/**
* Deploy the smart contract specified in the network configuration file.
* @return {object} Promise execution for namereg.
*/
async installSmartContract() {
let config = require(this.configPath);
let connection = burrowConnect(config, this.workspaceRoot);
let options = { objectReturn: true };
let burrow = monax.createInstance(connection.url, connection.account, options);
let data, abi, bytecode, contract;
try {
data = JSON.parse(fs.readFileSync(CaliperUtils.resolvePath(config.contract.path, this.workspaceRoot)).toString());
abi = data.Abi;
bytecode = data.Evm.Bytecode.Object;
contract = await burrow.contracts.deploy(abi, bytecode);
logger.info(`Contract: ${contract.address}`);
} catch (err) {
throw err;
}
let setPayload = {
Input: {
Address: Buffer.from(connection.account, 'hex'),
Amount: 50000
},
Name: 'DOUG',
Data: contract.address,
Fee: 5000
};
// this stores the contract address in a namereg for easy retrieval
return burrow.transact.NameTxSync(setPayload);
}
/**
* Return the Burrow context associated with the given callback module name.
* @param {string} name The name of the callback module as defined in the configuration files.
* @param {object} args Unused.
* @return {object} The assembled Burrow context.
* @async
*/
async getContext(name, args) {
let config = require(this.configPath);
let context = config.burrow.context;
if (typeof context === 'undefined') {
let connection = burrowConnect(config, this.workspaceRoot);
let options = { objectReturn: true };
let burrow = monax.createInstance(connection.url, connection.account, options);
// get the contract address from the namereg
let address = (await burrow.query.GetName({ Name: 'DOUG' })).Data;
context = { account: connection.account, address: address, burrow: burrow };
}
return Promise.resolve(context);
}
/**
* Release the given Burrow context.
* @param {object} context The Burrow context to release.
* @async
*/
async releaseContext(context) {
// nothing to do
}
/**
* Invoke a smart contract.
* @param {Object} context Context object.
* @param {String} contractID Identity of the contract.
* @param {String} contractVer Version of the contract.
* @param {Array} args Array of JSON formatted arguments for multiple transactions.
* @param {Number} timeout Request timeout, in seconds.
* @return {Promise<object>} The promise for the result of the execution.
*/
async invokeSmartContract(context, contractID, contractVer, args, timeout) {
let promises = [];
args.forEach((item, index) => {
promises.push(this.burrowTransaction(context, contractID, contractVer, item, timeout));
});
return await Promise.all(promises);
}
/**
* Submit a transaction to the burrow daemon with the specified options.
* @param {Object} context Context object.
* @param {String} contractID Identity of the contract.
* @param {String} contractVer Version of the contract.
* @param {Array} args Array of JSON formatted arguments for multiple transactions.
* @param {Number} timeout Request timeout, in seconds.
* @return {Promise<TxStatus>} Result and stats of the transaction invocation.
*/
async burrowTransaction(context, contractID, contractVer, args, timeout) {
let status = new TxStatus(args.account);
if (context.engine) {
context.engine.submitCallback(1);
}
let tx = {
Input: {
Address: Buffer.from(context.account, 'hex'),
Amount: args.money
},
Address: Buffer.from(context.address, 'hex'),
GasLimit: 5000,
Fee: 5000
};
try {
let execution = await context.burrow.transact.CallTxSync(tx);
status.SetID(execution.TxHash.toString());
status.SetStatusSuccess();
} catch (err) {
status.SetStatusFail();
}
return status;
}
/**
* Query the given smart contract according to the specified options.
* @param {object} context The Burrow context returned by {getContext}.
* @param {string} contractID The name of the contract.
* @param {string} contractVer The version of the contract.
* @param {string} key The argument to pass to the smart contract query.
* @param {string} [fcn=query] The contract query function name.
* @return {Promise<object>} The promise for the result of the execution.
*/
async queryState(context, contractID, contractVer, key, fcn = 'query') {
let status = new TxStatus();
if (context.engine) {
context.engine.submitCallback(1);
}
return new Promise(function (resolve, reject) {
context.burrow.query.GetAccount({ Address: Buffer.from(context.address, 'hex') }, function (error, data) {
if (error) {
status.SetStatusFail();
reject(error);
} else {
status.SetStatusSuccess();
resolve(data);
}
});
}).then(function (result) {
return status;
});
}
/**
* Get adapter specific transaction statistics.
* @param {JSON} stats txStatistics object
* @param {Array} results array of txStatus objects.
*/
getDefaultTxStats(stats, results) {
// empty
}
}
module.exports = Burrow;