├── .gitignore
├── .gitmodules
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── _config.yml
├── build-protobufs.sh
├── package.json
├── protobuf
├── api
│ └── api.proto
└── core
│ ├── Contract.proto
│ ├── Discover.proto
│ ├── Tron.proto
│ └── TronInventoryItems.proto
├── src
├── client
│ └── http.js
├── config.js
├── index.js
├── lib
│ ├── base58.js
│ ├── code.js
│ ├── sha.js
│ ├── sha256.js
│ ├── sha_dev.js
│ └── x64-core.js
├── protocol
│ ├── api
│ │ ├── api_grpc_pb.js
│ │ └── api_pb.js
│ └── core
│ │ ├── Contract_pb.js
│ │ ├── Discover_pb.js
│ │ ├── TronInventoryItems_pb.js
│ │ └── Tron_pb.js
├── signer
│ └── privateKeySigner.js
└── utils
│ ├── account.js
│ ├── address.js
│ ├── base64.js
│ ├── bytes.js
│ ├── crypto.js
│ ├── transactionBuilder.js
│ └── tronWeb.js
└── test
└── transactionBuilder.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # next.js build output
61 | .next
62 |
63 | # IDE
64 | .idea
65 |
66 | /protocol
67 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "protocol"]
2 | path = protocol
3 | url = https://github.com/tronprotocol/protocol
4 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | /protocol
2 | .idea
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "9"
4 | before_install:
5 | - "npm config set spin false"
6 | install:
7 | - npm install
8 | script:
9 | - npm test
10 |
11 | cache:
12 | directories:
13 | - node_modules
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) [2007] [TRON Foundation], Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | Tronscan Client
4 |
5 |
6 |
7 |
10 |
11 |
12 | How to Use
13 |
14 |
15 | # How to use
16 |
17 | ## Requirements
18 |
19 | * Node v9.8.0
20 |
21 | ## Running tests
22 |
23 | ```bash
24 | > npm test
25 | ```
26 |
27 | ## Usage
28 |
29 | Install the package
30 |
31 | ```bash
32 | > npm install @tronscanteam/apiclients
33 | ```
34 |
35 | Use the HTTP Client
36 |
37 | ```javascript
38 | import {Client} from "@tronscanteam/apiclients";
39 |
40 | const client = new Client();
41 |
42 | let recentBlocks = await client.getBlocks({
43 | sort: '-number',
44 | limit: 10,
45 | });
46 | ```
47 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/build-protobufs.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | docker run --rm -v $(pwd):$(pwd) -w $(pwd) znly/protoc \
4 | --proto_path=protobuf \
5 | --js_out=import_style=commonjs,binary:src/protocol \
6 | protobuf/core/*.proto protobuf/api/*.proto
7 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "_from": "@tronscanteam/apiclients@^",
3 | "_id": "@tronscanteam/apiclients@0.2.82",
4 | "_inBundle": false,
5 | "_integrity": "sha512-8fO4fTJXYAJeV4yK7KQ3CRP1sMEz8/aKq+sfwYdu8cTYqiWZurJ1M8Rf+iv03hSInHT95PaBv4AGYpCnusr/Ug==",
6 | "_location": "/@tronscanteam/apiclients",
7 | "_phantomChildren": {},
8 | "_requested": {
9 | "type": "range",
10 | "registry": true,
11 | "raw": "@tronscanteam/apiclients@^0.2.82",
12 | "name": "@tronscanteam/apiclients",
13 | "escapedName": "@tronscanteam%2fclient",
14 | "scope": "@tronscanteam",
15 | "rawSpec": "^0.2.82",
16 | "saveSpec": null,
17 | "fetchSpec": "^0.2.82"
18 | },
19 | "_requiredBy": [
20 | "/"
21 | ],
22 | "_resolved": "https://registry.npmjs.org/@tronscanteam/apiclients/-/client-0.2.82.tgz",
23 | "_shasum": "715171126ba7e60ff237016c497b207d11f7c31d",
24 | "_spec": "@tronscanteam/apiclients@^0.2.82",
25 | "_where": "/Users/Documents/project/project-front/tronscanteam-frontend",
26 | "author": {
27 | "name": "w-richard"
28 | },
29 | "bugs": {
30 | "url": "https://github.com/tronscanteam/tronscanteam-node-client/issues"
31 | },
32 | "bundleDependencies": false,
33 | "dependencies": {
34 | "axios": "^0.18.0",
35 | "babel-plugin-transform-class-properties": "^6.24.1",
36 | "babel-plugin-transform-object-rest-spread": "^6.26.0",
37 | "babel-preset-env": "^1.7.0",
38 | "babel-preset-es2015": "^6.24.1",
39 | "base-58": "^0.0.1",
40 | "btoa": "^1.2.1",
41 | "chai": "^4.1.2",
42 | "crypto-js": "^3.1.9-1",
43 | "elliptic": "^6.4.0",
44 | "google-protobuf": "^3.5.0",
45 | "js-sha3": "^0.7.0",
46 | "mocha": "^5.1.0",
47 | "nano-time": "^1.0.0",
48 | "qs": "^6.5.1"
49 | },
50 | "deprecated": false,
51 | "description": "Tronscan API Client",
52 | "homepage": "https://api.tronscan.org/",
53 | "keywords": [
54 | "tron"
55 | ],
56 | "license": "GPL-3.0",
57 | "main": "src/index.js",
58 | "name": "@tronscanteam/apiclients",
59 | "repository": {
60 | "type": "git",
61 | "url": "git://github.com/tronscan/tronscan-node-client.git"
62 | },
63 | "scripts": {
64 | "protoc:generate": "./protocol/protobuf-3.5.1/src/.libs/protoc --proto_path=protocol/protobuf-3.5.1/src --proto_path=protocol --grpc_out=./src/protocol --plugin=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin` --js_out=import_style=commonjs,binary:src/protocol protocol/core/*.proto protocol/api/*.proto",
65 | "protoc:install": "cd protocol && ./install-protobuf.sh",
66 | "test": "mocha",
67 | "test:watch": "mocha --watch"
68 | },
69 | "version": "0.2.82"
70 | }
71 |
--------------------------------------------------------------------------------
/protobuf/core/Contract.proto:
--------------------------------------------------------------------------------
1 | /*
2 | * java-tron is free software: you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation, either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * java-tron is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | */
15 |
16 | syntax = "proto3";
17 |
18 | package protocol;
19 |
20 | option java_package = "org.tron.protos"; //Specify the name of the package that generated the Java file
21 | option java_outer_classname = "Contract"; //Specify the class name of the generated Java file
22 | option go_package = "github.com/tronprotocol/grpc-gateway/core";
23 |
24 | import "core/Tron.proto";
25 |
26 | message AccountCreateContract {
27 | bytes owner_address = 1;
28 | bytes account_address = 2;
29 | AccountType type = 3;
30 | }
31 |
32 | // Update account name. Account name is not unique now.
33 | message AccountUpdateContract {
34 | bytes account_name = 1;
35 | bytes owner_address = 2;
36 | }
37 |
38 | // Set account id if the account has no id. Account id is unique and case insensitive.
39 | message SetAccountIdContract {
40 | bytes account_id = 1;
41 | bytes owner_address = 2;
42 | }
43 |
44 | message TransferContract {
45 | bytes owner_address = 1;
46 | bytes to_address = 2;
47 | int64 amount = 3;
48 | }
49 |
50 | message TransferAssetContract {
51 | bytes asset_name = 1; // this field is token name before the proposal ALLOW_SAME_TOKEN_NAME is active, otherwise it is token id and token is should be in string format.
52 | bytes owner_address = 2;
53 | bytes to_address = 3;
54 | int64 amount = 4;
55 | }
56 |
57 |
58 | message VoteAssetContract {
59 | bytes owner_address = 1;
60 | repeated bytes vote_address = 2;
61 | bool support = 3;
62 | int32 count = 5;
63 | }
64 |
65 | message VoteWitnessContract {
66 | message Vote {
67 | bytes vote_address = 1;
68 | int64 vote_count = 2;
69 | }
70 | bytes owner_address = 1;
71 | repeated Vote votes = 2;
72 | bool support = 3;
73 | }
74 |
75 | message UpdateSettingContract {
76 | bytes owner_address = 1;
77 | bytes contract_address = 2;
78 | int64 consume_user_resource_percent = 3;
79 | }
80 |
81 | message UpdateEnergyLimitContract {
82 | bytes owner_address = 1;
83 | bytes contract_address = 2;
84 | int64 origin_energy_limit = 3;
85 | }
86 |
87 | message ClearABIContract {
88 | bytes owner_address = 1;
89 | bytes contract_address = 2;
90 | }
91 |
92 | message WitnessCreateContract {
93 | bytes owner_address = 1;
94 | bytes url = 2;
95 | }
96 |
97 | message WitnessUpdateContract {
98 | bytes owner_address = 1;
99 | bytes update_url = 12;
100 | }
101 |
102 | message AssetIssueContract {
103 | string id = 41;
104 |
105 | message FrozenSupply {
106 | int64 frozen_amount = 1;
107 | int64 frozen_days = 2;
108 | }
109 | bytes owner_address = 1;
110 | bytes name = 2;
111 | bytes abbr = 3;
112 | int64 total_supply = 4;
113 | repeated FrozenSupply frozen_supply = 5;
114 | int32 trx_num = 6;
115 | int32 precision = 7;
116 | int32 num = 8;
117 | int64 start_time = 9;
118 | int64 end_time = 10;
119 | int64 order = 11; // useless
120 | int32 vote_score = 16;
121 | bytes description = 20;
122 | bytes url = 21;
123 | int64 free_asset_net_limit = 22;
124 | int64 public_free_asset_net_limit = 23;
125 | int64 public_free_asset_net_usage = 24;
126 | int64 public_latest_free_net_time = 25;
127 | }
128 |
129 | message ParticipateAssetIssueContract {
130 | bytes owner_address = 1;
131 | bytes to_address = 2;
132 | bytes asset_name = 3; // this field is token name before the proposal ALLOW_SAME_TOKEN_NAME is active, otherwise it is token id and token is should be in string format.
133 | int64 amount = 4; // the amount of drops
134 | }
135 |
136 |
137 | enum ResourceCode {
138 | BANDWIDTH = 0x00;
139 | ENERGY = 0x01;
140 | }
141 |
142 | message FreezeBalanceContract {
143 | bytes owner_address = 1;
144 | int64 frozen_balance = 2;
145 | int64 frozen_duration = 3;
146 |
147 | ResourceCode resource = 10;
148 | bytes receiver_address = 15;
149 | }
150 |
151 | message UnfreezeBalanceContract {
152 | bytes owner_address = 1;
153 |
154 | ResourceCode resource = 10;
155 | bytes receiver_address = 15;
156 | }
157 |
158 | message UnfreezeAssetContract {
159 | bytes owner_address = 1;
160 | }
161 |
162 | message WithdrawBalanceContract {
163 | bytes owner_address = 1;
164 | }
165 |
166 | message UpdateAssetContract {
167 | bytes owner_address = 1;
168 | bytes description = 2;
169 | bytes url = 3;
170 | int64 new_limit = 4;
171 | int64 new_public_limit = 5;
172 | }
173 |
174 | message ProposalCreateContract {
175 | bytes owner_address = 1;
176 | map parameters = 2;
177 | }
178 |
179 | message ProposalApproveContract {
180 | bytes owner_address = 1;
181 | int64 proposal_id = 2;
182 | bool is_add_approval = 3; // add or remove approval
183 | }
184 |
185 | message ProposalDeleteContract {
186 | bytes owner_address = 1;
187 | int64 proposal_id = 2;
188 | }
189 |
190 | message CreateSmartContract {
191 | bytes owner_address = 1;
192 | SmartContract new_contract = 2;
193 | int64 call_token_value = 3;
194 | int64 token_id = 4;
195 | }
196 |
197 | message TriggerSmartContract {
198 | bytes owner_address = 1;
199 | bytes contract_address = 2;
200 | int64 call_value = 3;
201 | bytes data = 4;
202 | int64 call_token_value = 5;
203 | int64 token_id = 6;
204 | }
205 |
206 | message BuyStorageContract {
207 | bytes owner_address = 1;
208 | int64 quant = 2; // trx quantity for buy storage (sun)
209 | }
210 |
211 | message BuyStorageBytesContract {
212 | bytes owner_address = 1;
213 | int64 bytes = 2; // storage bytes for buy
214 | }
215 |
216 | message SellStorageContract {
217 | bytes owner_address = 1;
218 | int64 storage_bytes = 2;
219 | }
220 |
221 | message ExchangeCreateContract {
222 | bytes owner_address = 1;
223 | bytes first_token_id = 2;
224 | int64 first_token_balance = 3;
225 | bytes second_token_id = 4;
226 | int64 second_token_balance = 5;
227 | }
228 |
229 | message ExchangeInjectContract {
230 | bytes owner_address = 1;
231 | int64 exchange_id = 2;
232 | bytes token_id = 3;
233 | int64 quant = 4;
234 | }
235 |
236 | message ExchangeWithdrawContract {
237 | bytes owner_address = 1;
238 | int64 exchange_id = 2;
239 | bytes token_id = 3;
240 | int64 quant = 4;
241 | }
242 |
243 | message ExchangeTransactionContract {
244 | bytes owner_address = 1;
245 | int64 exchange_id = 2;
246 | bytes token_id = 3;
247 | int64 quant = 4;
248 | int64 expected = 5;
249 | }
250 |
251 | message AccountPermissionUpdateContract {
252 | bytes owner_address = 1;
253 | Permission owner = 2; //Empty is invalidate
254 | Permission witness = 3;//Can be empty
255 | repeated Permission actives = 4;//Empty is invalidate
256 | }
257 |
258 | message UpdateBrokerageContract {
259 | bytes owner_address = 1;
260 | int32 brokerage = 2; // 1 mean 1%
261 | }
--------------------------------------------------------------------------------
/protobuf/core/Discover.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package protocol;
4 |
5 |
6 | option java_package = "org.tron.protos"; //Specify the name of the package that generated the Java file
7 | option java_outer_classname = "Discover"; //Specify the class name of the generated Java file
8 | option go_package = "github.com/tronprotocol/grpc-gateway/core";
9 |
10 | message Endpoint {
11 | bytes address = 1;
12 | int32 port = 2;
13 | bytes nodeId = 3;
14 | }
15 |
16 | message PingMessage {
17 | Endpoint from = 1;
18 | Endpoint to = 2;
19 | int32 version = 3;
20 | int64 timestamp = 4;
21 | }
22 |
23 | message PongMessage {
24 | Endpoint from = 1;
25 | int32 echo = 2;
26 | int64 timestamp = 3;
27 | }
28 |
29 | message FindNeighbours {
30 | Endpoint from = 1;
31 | bytes targetId = 2;
32 | int64 timestamp = 3;
33 | }
34 |
35 | message Neighbours {
36 | Endpoint from = 1;
37 | repeated Endpoint neighbours = 2;
38 | int64 timestamp = 3;
39 | }
40 |
41 | message BackupMessage {
42 | bool flag = 1;
43 | int32 priority = 2;
44 | }
--------------------------------------------------------------------------------
/protobuf/core/Tron.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | import "google/protobuf/any.proto";
4 | import "core/Discover.proto";
5 |
6 | package protocol;
7 |
8 |
9 | option java_package = "org.tron.protos"; //Specify the name of the package that generated the Java file
10 | option java_outer_classname = "Protocol"; //Specify the class name of the generated Java file
11 | option go_package = "github.com/tronprotocol/grpc-gateway/core";
12 |
13 | enum AccountType {
14 | Normal = 0;
15 | AssetIssue = 1;
16 | Contract = 2;
17 | }
18 |
19 | // AccountId, (name, address) use name, (null, address) use address, (name, null) use name,
20 | message AccountId {
21 | bytes name = 1;
22 | bytes address = 2;
23 | }
24 |
25 | // vote message
26 | message Vote {
27 | // the super rep address
28 | bytes vote_address = 1;
29 | // the vote num to this super rep.
30 | int64 vote_count = 2;
31 | }
32 |
33 | // Proposal
34 | message Proposal {
35 | int64 proposal_id = 1;
36 | bytes proposer_address = 2;
37 | map parameters = 3;
38 | int64 expiration_time = 4;
39 | int64 create_time = 5;
40 | repeated bytes approvals = 6;
41 | enum State {
42 | PENDING = 0;
43 | DISAPPROVED = 1;
44 | APPROVED = 2;
45 | CANCELED = 3;
46 | }
47 | State state = 7;
48 | }
49 |
50 | // Exchange
51 | message Exchange {
52 | int64 exchange_id = 1;
53 | bytes creator_address = 2;
54 | int64 create_time = 3;
55 | bytes first_token_id = 6;
56 | int64 first_token_balance = 7;
57 | bytes second_token_id = 8;
58 | int64 second_token_balance = 9;
59 | }
60 |
61 | message ChainParameters {
62 | repeated ChainParameter chainParameter = 1;
63 | message ChainParameter {
64 | string key = 1;
65 | int64 value = 2;
66 | }
67 | }
68 |
69 | /* Account */
70 | message Account {
71 | /* frozen balance */
72 | message Frozen {
73 | int64 frozen_balance = 1; // the frozen trx balance
74 | int64 expire_time = 2; // the expire time
75 | }
76 | // account nick name
77 | bytes account_name = 1;
78 | AccountType type = 2;
79 | // the create address
80 | bytes address = 3;
81 | // the trx balance
82 | int64 balance = 4;
83 | // the votes
84 | repeated Vote votes = 5;
85 | // the other asset owned by this account
86 | map asset = 6;
87 |
88 | // the other asset owned by this account,key is assetId
89 | map assetV2 = 56;
90 |
91 | // the frozen balance for bandwidth
92 | repeated Frozen frozen = 7;
93 | // bandwidth, get from frozen
94 | int64 net_usage = 8;
95 | //Frozen balance provided by other accounts to this account
96 | int64 acquired_delegated_frozen_balance_for_bandwidth = 41;
97 | //Freeze and provide balances to other accounts
98 | int64 delegated_frozen_balance_for_bandwidth = 42;
99 |
100 | // this account create time
101 | int64 create_time = 0x09;
102 | // this last operation time, including transfer, voting and so on. //FIXME fix grammar
103 | int64 latest_opration_time = 10;
104 | // witness block producing allowance
105 | int64 allowance = 0x0B;
106 | // last withdraw time
107 | int64 latest_withdraw_time = 0x0C;
108 | // not used so far
109 | bytes code = 13;
110 | bool is_witness = 14;
111 | bool is_committee = 15;
112 | // frozen asset(for asset issuer)
113 | repeated Frozen frozen_supply = 16;
114 | // asset_issued_name
115 | bytes asset_issued_name = 17;
116 | bytes asset_issued_ID = 57;
117 | map latest_asset_operation_time = 18;
118 | map latest_asset_operation_timeV2 = 58;
119 | int64 free_net_usage = 19;
120 | map free_asset_net_usage = 20;
121 | map free_asset_net_usageV2 = 59;
122 | int64 latest_consume_time = 21;
123 | int64 latest_consume_free_time = 22;
124 |
125 | // the identity of this account, case insensitive
126 | bytes account_id = 23;
127 |
128 | message AccountResource {
129 | // energy resource, get from frozen
130 | int64 energy_usage = 1;
131 | // the frozen balance for energy
132 | Frozen frozen_balance_for_energy = 2;
133 | int64 latest_consume_time_for_energy = 3;
134 |
135 | //Frozen balance provided by other accounts to this account
136 | int64 acquired_delegated_frozen_balance_for_energy = 4;
137 | //Frozen balances provided to other accounts
138 | int64 delegated_frozen_balance_for_energy = 5;
139 |
140 | // storage resource, get from market
141 | int64 storage_limit = 6;
142 | int64 storage_usage = 7;
143 | int64 latest_exchange_storage_time = 8;
144 |
145 | }
146 | AccountResource account_resource = 26;
147 | bytes codeHash = 30;
148 | Permission owner_permission = 31;
149 | Permission witness_permission = 32;
150 | repeated Permission active_permission = 33;
151 | }
152 |
153 |
154 | message Key {
155 | bytes address = 1;
156 | int64 weight = 2;
157 | }
158 |
159 | message DelegatedResource {
160 | bytes from = 1;
161 | bytes to = 2;
162 | int64 frozen_balance_for_bandwidth = 3;
163 | int64 frozen_balance_for_energy = 4;
164 | int64 expire_time_for_bandwidth = 5;
165 | int64 expire_time_for_energy = 6;
166 | }
167 |
168 | message authority {
169 | AccountId account = 1;
170 | bytes permission_name = 2;
171 | }
172 |
173 | message Permission {
174 | enum PermissionType {
175 | Owner = 0;
176 | Witness = 1;
177 | Active = 2;
178 | }
179 | PermissionType type = 1;
180 | int32 id = 2; //Owner id=0, Witness id=1, Active id start by 2
181 | string permission_name = 3;
182 | int64 threshold = 4;
183 | int32 parent_id = 5;
184 | bytes operations = 6; //1 bit 1 contract
185 | repeated Key keys = 7;
186 | }
187 |
188 | // Witness
189 | message Witness {
190 | bytes address = 1;
191 | int64 voteCount = 2;
192 | bytes pubKey = 3;
193 | string url = 4;
194 | int64 totalProduced = 5;
195 | int64 totalMissed = 6;
196 | int64 latestBlockNum = 7;
197 | int64 latestSlotNum = 8;
198 | bool isJobs = 9;
199 | }
200 |
201 | // Vote Change
202 | message Votes {
203 | bytes address = 1;
204 | repeated Vote old_votes = 2;
205 | repeated Vote new_votes = 3;
206 | }
207 |
208 | // Transcation
209 |
210 | message TXOutput {
211 | int64 value = 1;
212 | bytes pubKeyHash = 2;
213 | }
214 |
215 | message TXInput {
216 | message raw {
217 | bytes txID = 1;
218 | int64 vout = 2;
219 | bytes pubKey = 3;
220 | }
221 | raw raw_data = 1;
222 | bytes signature = 4;
223 | }
224 |
225 | message TXOutputs {
226 | repeated TXOutput outputs = 1;
227 | }
228 |
229 | message ResourceReceipt {
230 | int64 energy_usage = 1;
231 | int64 energy_fee = 2;
232 | int64 origin_energy_usage = 3;
233 | int64 energy_usage_total = 4;
234 | int64 net_usage = 5;
235 | int64 net_fee = 6;
236 | Transaction.Result.contractResult result = 7;
237 | }
238 |
239 | message Transaction {
240 | message Contract {
241 | enum ContractType {
242 | AccountCreateContract = 0;
243 | TransferContract = 1;
244 | TransferAssetContract = 2;
245 | VoteAssetContract = 3;
246 | VoteWitnessContract = 4;
247 | WitnessCreateContract = 5;
248 | AssetIssueContract = 6;
249 | WitnessUpdateContract = 8;
250 | ParticipateAssetIssueContract = 9;
251 | AccountUpdateContract = 10;
252 | FreezeBalanceContract = 11;
253 | UnfreezeBalanceContract = 12;
254 | WithdrawBalanceContract = 13;
255 | UnfreezeAssetContract = 14;
256 | UpdateAssetContract = 15;
257 | ProposalCreateContract = 16;
258 | ProposalApproveContract = 17;
259 | ProposalDeleteContract = 18;
260 | SetAccountIdContract = 19;
261 | CustomContract = 20;
262 | // BuyStorageContract = 21;
263 | // BuyStorageBytesContract = 22;
264 | // SellStorageContract = 23;
265 | CreateSmartContract = 30;
266 | TriggerSmartContract = 31;
267 | GetContract = 32;
268 | UpdateSettingContract = 33;
269 | ExchangeCreateContract = 41;
270 | ExchangeInjectContract = 42;
271 | ExchangeWithdrawContract = 43;
272 | ExchangeTransactionContract = 44;
273 | UpdateEnergyLimitContract = 45;
274 | AccountPermissionUpdateContract = 46;
275 | ClearABIContract = 48;
276 | UpdateBrokerageContract = 49;
277 | }
278 | ContractType type = 1;
279 | google.protobuf.Any parameter = 2;
280 | bytes provider = 3;
281 | bytes ContractName = 4;
282 | int32 Permission_id = 5;
283 | }
284 |
285 | message Result {
286 | enum code {
287 | SUCESS = 0;
288 | FAILED = 1;
289 | }
290 | enum contractResult {
291 | DEFAULT = 0;
292 | SUCCESS = 1;
293 | REVERT = 2;
294 | BAD_JUMP_DESTINATION = 3;
295 | OUT_OF_MEMORY = 4;
296 | PRECOMPILED_CONTRACT = 5;
297 | STACK_TOO_SMALL = 6;
298 | STACK_TOO_LARGE = 7;
299 | ILLEGAL_OPERATION = 8;
300 | STACK_OVERFLOW = 9;
301 | OUT_OF_ENERGY = 10;
302 | OUT_OF_TIME = 11;
303 | JVM_STACK_OVER_FLOW = 12;
304 | UNKNOWN = 13;
305 | TRANSFER_FAILED = 14;
306 | }
307 | int64 fee = 1;
308 | code ret = 2;
309 | contractResult contractRet = 3;
310 |
311 | string assetIssueID = 14;
312 | int64 withdraw_amount = 15;
313 | int64 unfreeze_amount = 16;
314 | int64 exchange_received_amount = 18;
315 | int64 exchange_inject_another_amount = 19;
316 | int64 exchange_withdraw_another_amount = 20;
317 | int64 exchange_id = 21;
318 | }
319 |
320 | message raw {
321 | bytes ref_block_bytes = 1;
322 | int64 ref_block_num = 3;
323 | bytes ref_block_hash = 4;
324 | int64 expiration = 8;
325 | repeated authority auths = 9;
326 | // data not used
327 | bytes data = 10;
328 | //only support size = 1, repeated list here for extension
329 | repeated Contract contract = 11;
330 | // scripts not used
331 | bytes scripts = 12;
332 | int64 timestamp = 14;
333 | int64 fee_limit = 18;
334 | }
335 |
336 | raw raw_data = 1;
337 | // only support size = 1, repeated list here for muti-sig extension
338 | repeated bytes signature = 2;
339 | repeated Result ret = 5;
340 | }
341 |
342 | message TransactionInfo {
343 | enum code {
344 | SUCESS = 0;
345 | FAILED = 1;
346 | }
347 | message Log {
348 | bytes address = 1;
349 | repeated bytes topics = 2;
350 | bytes data = 3;
351 | }
352 | bytes id = 1;
353 | int64 fee = 2;
354 | int64 blockNumber = 3;
355 | int64 blockTimeStamp = 4;
356 | repeated bytes contractResult = 5;
357 | bytes contract_address = 6;
358 | ResourceReceipt receipt = 7;
359 | repeated Log log = 8;
360 | code result = 9;
361 | bytes resMessage = 10;
362 |
363 | string assetIssueID = 14;
364 | int64 withdraw_amount = 15;
365 | int64 unfreeze_amount = 16;
366 | repeated InternalTransaction internal_transactions = 17;
367 | int64 exchange_received_amount = 18;
368 | int64 exchange_inject_another_amount = 19;
369 | int64 exchange_withdraw_another_amount = 20;
370 | int64 exchange_id = 21;
371 | }
372 |
373 | message Transactions {
374 | repeated Transaction transactions = 1;
375 | }
376 |
377 | message TransactionSign {
378 | Transaction transaction = 1;
379 | bytes privateKey = 2;
380 | }
381 |
382 | message BlockHeader {
383 | message raw {
384 | int64 timestamp = 1;
385 | bytes txTrieRoot = 2;
386 | bytes parentHash = 3;
387 | //bytes nonce = 5;
388 | //bytes difficulty = 6;
389 | int64 number = 7;
390 | int64 witness_id = 8;
391 | bytes witness_address = 9;
392 | int32 version = 10;
393 | bytes accountStateRoot = 11;
394 | }
395 | raw raw_data = 1;
396 | bytes witness_signature = 2;
397 | }
398 |
399 | // block
400 | message Block {
401 | repeated Transaction transactions = 1;
402 | BlockHeader block_header = 2;
403 | }
404 |
405 | message ChainInventory {
406 | message BlockId {
407 | bytes hash = 1;
408 | int64 number = 2;
409 | }
410 | repeated BlockId ids = 1;
411 | int64 remain_num = 2;
412 | }
413 |
414 | // Inventory
415 | message BlockInventory {
416 | enum Type {
417 | SYNC = 0;
418 | ADVTISE = 1;
419 | FETCH = 2;
420 | }
421 |
422 | message BlockId {
423 | bytes hash = 1;
424 | int64 number = 2;
425 | }
426 | repeated BlockId ids = 1;
427 | Type type = 2;
428 | }
429 |
430 | message Inventory {
431 | enum InventoryType {
432 | TRX = 0;
433 | BLOCK = 1;
434 | }
435 | InventoryType type = 1;
436 | repeated bytes ids = 2;
437 | }
438 |
439 | message Items {
440 | enum ItemType {
441 | ERR = 0;
442 | TRX = 1;
443 | BLOCK = 2;
444 | BLOCKHEADER = 3;
445 | }
446 |
447 | ItemType type = 1;
448 | repeated Block blocks = 2;
449 | repeated BlockHeader block_headers = 3;
450 | repeated Transaction transactions = 4;
451 | }
452 |
453 | // DynamicProperties
454 | message DynamicProperties {
455 | int64 last_solidity_block_num = 1;
456 | }
457 |
458 | enum ReasonCode {
459 | REQUESTED = 0x00;
460 | BAD_PROTOCOL = 0x02;
461 | TOO_MANY_PEERS = 0x04;
462 | DUPLICATE_PEER = 0x05;
463 | INCOMPATIBLE_PROTOCOL = 0x06;
464 | NULL_IDENTITY = 0x07;
465 | PEER_QUITING = 0x08;
466 | UNEXPECTED_IDENTITY = 0x09;
467 | LOCAL_IDENTITY = 0x0A;
468 | PING_TIMEOUT = 0x0B;
469 | USER_REASON = 0x10;
470 | RESET = 0x11;
471 | SYNC_FAIL = 0x12;
472 | FETCH_FAIL = 0x13;
473 | BAD_TX = 0x14;
474 | BAD_BLOCK = 0x15;
475 | FORKED = 0x16;
476 | UNLINKABLE = 0x17;
477 | INCOMPATIBLE_VERSION = 0x18;
478 | INCOMPATIBLE_CHAIN = 0x19;
479 | TIME_OUT = 0x20;
480 | CONNECT_FAIL = 0x21;
481 | TOO_MANY_PEERS_WITH_SAME_IP = 0x22;
482 | UNKNOWN = 0xFF;
483 | }
484 |
485 | message DisconnectMessage {
486 | ReasonCode reason = 1;
487 | }
488 |
489 | message HelloMessage {
490 | message BlockId {
491 | bytes hash = 1;
492 | int64 number = 2;
493 | }
494 |
495 | Endpoint from = 1;
496 | int32 version = 2;
497 | int64 timestamp = 3;
498 | BlockId genesisBlockId = 4;
499 | BlockId solidBlockId = 5;
500 | BlockId headBlockId = 6;
501 | }
502 |
503 | message SmartContract {
504 | message ABI {
505 | message Entry {
506 | enum EntryType {
507 | UnknownEntryType = 0;
508 | Constructor = 1;
509 | Function = 2;
510 | Event = 3;
511 | Fallback = 4;
512 | }
513 | message Param {
514 | bool indexed = 1;
515 | string name = 2;
516 | string type = 3;
517 | // SolidityType type = 3;
518 | }
519 | enum StateMutabilityType {
520 | UnknownMutabilityType = 0;
521 | Pure = 1;
522 | View = 2;
523 | Nonpayable = 3;
524 | Payable = 4;
525 | }
526 |
527 | bool anonymous = 1;
528 | bool constant = 2;
529 | string name = 3;
530 | repeated Param inputs = 4;
531 | repeated Param outputs = 5;
532 | EntryType type = 6;
533 | bool payable = 7;
534 | StateMutabilityType stateMutability = 8;
535 | }
536 | repeated Entry entrys = 1;
537 | }
538 | bytes origin_address = 1;
539 | bytes contract_address = 2;
540 | ABI abi = 3;
541 | bytes bytecode = 4;
542 | int64 call_value = 5;
543 | int64 consume_user_resource_percent = 6;
544 | string name = 7;
545 | int64 origin_energy_limit = 8;
546 | bytes code_hash = 9;
547 | bytes trx_hash = 10;
548 | }
549 |
550 | message InternalTransaction {
551 | // internalTransaction identity, the root InternalTransaction hash
552 | // should equals to root transaction id.
553 | bytes hash = 1;
554 | // the one send trx (TBD: or token) via function
555 | bytes caller_address = 2;
556 | // the one recieve trx (TBD: or token) via function
557 | bytes transferTo_address = 3;
558 | message CallValueInfo {
559 | // trx (TBD: or token) value
560 | int64 callValue = 1;
561 | // TBD: tokenName, trx should be empty
562 | string tokenId = 2;
563 | }
564 | repeated CallValueInfo callValueInfo = 4;
565 | bytes note = 5;
566 | bool rejected = 6;
567 | }
568 |
569 | message DelegatedResourceAccountIndex {
570 | bytes account = 1;
571 | repeated bytes fromAccounts = 2;
572 | repeated bytes toAccounts = 3;
573 | }
574 |
575 | message NodeInfo {
576 | int64 beginSyncNum = 1;
577 | string block = 2;
578 | string solidityBlock = 3;
579 | //connect information
580 | int32 currentConnectCount = 4;
581 | int32 activeConnectCount = 5;
582 | int32 passiveConnectCount = 6;
583 | int64 totalFlow = 7;
584 | repeated PeerInfo peerInfoList = 8;
585 | ConfigNodeInfo configNodeInfo = 9;
586 | MachineInfo machineInfo = 10;
587 | map cheatWitnessInfoMap = 11;
588 |
589 | message PeerInfo {
590 | string lastSyncBlock = 1;
591 | int64 remainNum = 2;
592 | int64 lastBlockUpdateTime = 3;
593 | bool syncFlag = 4;
594 | int64 headBlockTimeWeBothHave = 5;
595 | bool needSyncFromPeer = 6;
596 | bool needSyncFromUs = 7;
597 | string host = 8;
598 | int32 port = 9;
599 | string nodeId = 10;
600 | int64 connectTime = 11;
601 | double avgLatency = 12;
602 | int32 syncToFetchSize = 13;
603 | int64 syncToFetchSizePeekNum = 14;
604 | int32 syncBlockRequestedSize = 15;
605 | int64 unFetchSynNum = 16;
606 | int32 blockInPorcSize = 17;
607 | string headBlockWeBothHave = 18;
608 | bool isActive = 19;
609 | int32 score = 20;
610 | int32 nodeCount = 21;
611 | int64 inFlow = 22;
612 | int32 disconnectTimes = 23;
613 | string localDisconnectReason = 24;
614 | string remoteDisconnectReason = 25;
615 | }
616 |
617 | message ConfigNodeInfo {
618 | string codeVersion = 1;
619 | string p2pVersion = 2;
620 | int32 listenPort = 3;
621 | bool discoverEnable = 4;
622 | int32 activeNodeSize = 5;
623 | int32 passiveNodeSize = 6;
624 | int32 sendNodeSize = 7;
625 | int32 maxConnectCount = 8;
626 | int32 sameIpMaxConnectCount = 9;
627 | int32 backupListenPort = 10;
628 | int32 backupMemberSize = 11;
629 | int32 backupPriority = 12;
630 | int32 dbVersion = 13;
631 | int32 minParticipationRate = 14;
632 | bool supportConstant = 15;
633 | double minTimeRatio = 16;
634 | double maxTimeRatio = 17;
635 | int64 allowCreationOfContracts = 18;
636 | int64 allowAdaptiveEnergy = 19;
637 | }
638 |
639 | message MachineInfo {
640 | int32 threadCount = 1;
641 | int32 deadLockThreadCount = 2;
642 | int32 cpuCount = 3;
643 | int64 totalMemory = 4;
644 | int64 freeMemory = 5;
645 | double cpuRate = 6;
646 | string javaVersion = 7;
647 | string osName = 8;
648 | int64 jvmTotalMemoery = 9;
649 | int64 jvmFreeMemory = 10;
650 | double processCpuRate = 11;
651 | repeated MemoryDescInfo memoryDescInfoList = 12;
652 | repeated DeadLockThreadInfo deadLockThreadInfoList = 13;
653 |
654 | message MemoryDescInfo {
655 | string name = 1;
656 | int64 initSize = 2;
657 | int64 useSize = 3;
658 | int64 maxSize = 4;
659 | double useRate = 5;
660 | }
661 |
662 | message DeadLockThreadInfo {
663 | string name = 1;
664 | string lockName = 2;
665 | string lockOwner = 3;
666 | string state = 4;
667 | int64 blockTime = 5;
668 | int64 waitTime = 6;
669 | string stackTrace = 7;
670 | }
671 | }
672 | }
--------------------------------------------------------------------------------
/protobuf/core/TronInventoryItems.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package protocol;
4 |
5 | option java_package = "org.tron.protos"; //Specify the name of the package that generated the Java file
6 | option java_outer_classname = "TronInventoryItems"; //Specify the class name of the generated Java file
7 | option go_package = "github.com/tronprotocol/grpc-gateway/core";
8 |
9 | message InventoryItems {
10 | int32 type = 1;
11 | repeated bytes items = 2;
12 | }
--------------------------------------------------------------------------------
/src/client/http.js:
--------------------------------------------------------------------------------
1 | const xhr = require("axios");
2 | const {
3 | buildTransferTransaction, buildVote, buildAssetParticipate, buildFreezeBalance, buildAssetIssue,
4 | buildUnfreezeBalance, buildAccountUpdate, buildWitnessUpdate, buildWithdrawBalance, buildWitnessCreate,
5 | buildUnfreezeAsset, buildExchangeCreate, buildExchangeInject, buildExchangeWithdraw, buildTransactionExchange,
6 | buildTransferHexStr, buildTriggerSmartContract,getTriggerSmartContractParameterValue, getTransferContractParameterValue,
7 | getTransferAssetContractParameterValue,getAccountPermissionUpdateContractParameterValue
8 | } = require("../utils/transactionBuilder");
9 | const {hexStr2byteArray} = require("../lib/code");
10 | const PrivateKeySigner = require("../signer/privateKeySigner");
11 | const encodeString = require("../lib/code").encodeString;
12 | const pkToAddress = require("../utils/crypto").pkToAddress;
13 |
14 | function longToByteArray(/*long*/long) {
15 | // we want to represent the input as a 8-bytes array
16 | var byteArray = [0, 0, 0, 0, 0, 0, 0, 0];
17 |
18 | for (var index = 0; index < byteArray.length; index++) {
19 | var byte = long & 0xff;
20 | byteArray [index] = byte;
21 | long = (long - byte) / 256;
22 | }
23 |
24 | return byteArray;
25 | }
26 |
27 | function byteArrayToLong(/*byte[]*/byteArray) {
28 | var value = 0;
29 | for (var i = byteArray.length - 1; i >= 0; i--) {
30 | value = (value * 256) + byteArray[i];
31 | }
32 |
33 | return value;
34 | }
35 |
36 | class ApiClient {
37 |
38 | constructor(url) {
39 | this.apiUrl = url;
40 | this.signer = null;
41 | }
42 |
43 | setSigner(signer) {
44 | this.signer = signer;
45 | }
46 |
47 | send(token, from, to, amount) {
48 | let transaction = buildTransferTransaction(token, from, to, amount);
49 | return (pk) => this.sendTransaction(pk, transaction);
50 | }
51 |
52 | getSendHexStr(token, from, to, amount) {
53 | let hexStr = buildTransferHexStr(token, from, to, amount);
54 | return hexStr;
55 | }
56 |
57 |
58 | sendWithNote(token, from, to, amount, note) {
59 | let transaction = buildTransferTransaction(token, from, to, amount);
60 | if (note.length > 0) {
61 | let rawData = transaction.getRawData();
62 | rawData.setData(encodeString(encodeURIComponent(note)));
63 | transaction.setRawData(rawData);
64 | }
65 |
66 | return (pk) => this.sendTransaction(pk, transaction);
67 | }
68 |
69 | async addRef(transaction) {
70 |
71 | let latestBlock = await this.getLatestBlock();
72 |
73 | let latestBlockHash = latestBlock.hash;
74 | let latestBlockNum = latestBlock.number;
75 |
76 | let numBytes = longToByteArray(latestBlockNum);
77 | numBytes.reverse();
78 | let hashBytes = hexStr2byteArray(latestBlockHash);
79 |
80 | let generateBlockId = [...numBytes.slice(0, 8), ...hashBytes.slice(8, hashBytes.length - 1)];
81 |
82 | let rawData = transaction.getRawData();
83 | rawData.setRefBlockHash(Uint8Array.from(generateBlockId.slice(8, 16)));
84 | rawData.setRefBlockBytes(Uint8Array.from(numBytes.slice(6, 8)));
85 | rawData.setExpiration(latestBlock.timestamp + (60 * 5 * 1000));
86 |
87 | transaction.setRawData(rawData);
88 | return transaction;
89 | }
90 |
91 | getSigner(pk) {
92 | return this.signer || new PrivateKeySigner(pk);
93 | }
94 |
95 | async sendTransaction(pk, transaction) {
96 | transaction = await this.addRef(transaction);
97 | let privateKeySigner = this.getSigner(pk);
98 | let {hex} = await privateKeySigner.signTransaction(transaction);
99 | let {data} = await xhr.post(`${this.apiUrl}/api/broadcast`, {
100 | transaction: hex,
101 | });
102 |
103 | return data;
104 | }
105 |
106 | async sendTransactionRaw(transactionHex) {
107 | let {data} = await xhr.post(`${this.apiUrl}/api/broadcast`, {
108 | transaction: transactionHex,
109 | });
110 |
111 | return data;
112 | }
113 |
114 | async auth(pk) {
115 | let transaction = buildWitnessUpdate(pkToAddress(pk), "UPDATE_SR");
116 | let privateKeySigner = this.getSigner(pk);
117 | let {hex} = await privateKeySigner.signTransaction(transaction);
118 | let {data} = await xhr.post(`${this.apiUrl}/api/auth`, {
119 | transaction: hex,
120 | });
121 |
122 | return data.key;
123 | }
124 |
125 | async updateSuperRepresentative(key, sr) {
126 | await xhr.post(`${this.apiUrl}/api/account/${sr.address}/sr`, sr, {
127 | headers: {
128 | "X-Key": key,
129 | }
130 | });
131 | }
132 |
133 | async getSuperRepresentative(address) {
134 | let {data} = await xhr.get(`${this.apiUrl}/api/account/sr?address=`+address);
135 | return data;
136 | }
137 |
138 | updateAccountName(address, name) {
139 | let transaction = buildAccountUpdate(address, name);
140 | return (pk) => this.sendTransaction(pk, transaction);
141 | }
142 |
143 | updateWitnessUrl(address, url) {
144 | let transaction = buildWitnessUpdate(address, url);
145 | return (pk) => this.sendTransaction(pk, transaction);
146 | }
147 |
148 | withdrawBalance(address) {
149 | let transaction = buildWithdrawBalance(address);
150 | return (pk) => this.sendTransaction(pk, transaction);
151 | }
152 |
153 | freezeBalance(address, amount, duration, resource,receiver) {
154 | let transaction = buildFreezeBalance(address, amount, duration, resource,receiver);
155 | return (pk) => this.sendTransaction(pk, transaction);
156 | }
157 |
158 | unfreezeBalance(address, resource,receiver) {
159 | let transaction = buildUnfreezeBalance(address, resource,receiver);
160 | return (pk) => this.sendTransaction(pk, transaction);
161 | }
162 |
163 | unfreezeAssets(address) {
164 | let transaction = buildUnfreezeAsset(address);
165 | return (pk) => this.sendTransaction(pk, transaction);
166 | }
167 |
168 | applyForDelegate(address, url) {
169 | let transaction = buildWitnessCreate(address, url);
170 | return (pk) => this.sendTransaction(pk, transaction);
171 | }
172 |
173 | voteForWitnesses(address, votes) {
174 | let transaction = buildVote(address, votes);
175 | return (pk) => this.sendTransaction(pk, transaction);
176 | }
177 |
178 | participateAsset(address, issuerAddress, token, amount) {
179 | let transaction = buildAssetParticipate(address, issuerAddress, token, amount);
180 | return (pk) => this.sendTransaction(pk, transaction);
181 | }
182 |
183 | createToken(options) {
184 | let transaction = buildAssetIssue(options);
185 | return (pk) => this.sendTransaction(pk, transaction);
186 | }
187 |
188 | createExchange(address, firstTokenID, secondTokenId, firstTokenBalance, secondTokenBalance) {
189 | let transaction = buildExchangeCreate(address, firstTokenID, secondTokenId, firstTokenBalance, secondTokenBalance);
190 | return (pk) => this.sendTransaction(pk, transaction);
191 | }
192 |
193 | injectExchange(address, exchangeId, tokenId, quant) {
194 | let transaction = buildExchangeInject(address, exchangeId, tokenId, quant);
195 | return (pk) => this.sendTransaction(pk, transaction);
196 | }
197 |
198 | withdrawExchange(address, exchangeId, tokenId, quant) {
199 | let transaction = buildExchangeWithdraw(address, exchangeId, tokenId, quant);
200 | return (pk) => this.sendTransaction(pk, transaction);
201 | }
202 |
203 | transactionExchange(address, exchange_id, token_id, quant, expected) {
204 | let transaction = buildTransactionExchange(address, exchange_id, token_id, quant, expected);
205 | return (pk) => this.sendTransaction(pk, transaction);
206 | }
207 |
208 | async getBlocks(options = {}) {
209 | let {data} = await xhr.get(`${this.apiUrl}/api/block`, {
210 | params: Object.assign({
211 | sort: '-number',
212 | limit: 50,
213 | count: true,
214 | }, options),
215 | });
216 |
217 | return {
218 | blocks: data.data,
219 | total: data.total,
220 | rangeTotal:data.rangeTotal,
221 | };
222 | }
223 |
224 | async getLatestBlock() {
225 | let {data} = await xhr.get(`${this.apiUrl}/api/block/latest`);
226 | return data;
227 | }
228 |
229 | async getTransactions(options = {}) {
230 | let {data} = await xhr.get(`${this.apiUrl}/api/transaction`, {
231 | params: Object.assign({
232 | sort: '-timestamp',
233 | count: true,
234 | limit: 50,
235 | }, options)
236 | });
237 |
238 | return {
239 | transactions: data.data,
240 | contractMap:data.contractMap,
241 | contractInfo:data.contractInfo,
242 | total: data.total,
243 | rangeTotal: data.rangeTotal,
244 | wholeChainTxCount: data.wholeChainTxCount
245 | };
246 | }
247 |
248 | async getTransfers(options = {}) {
249 | let {data} = await xhr.get(`${this.apiUrl}/api/transfer`, {
250 | params: Object.assign({
251 | sort: '-timestamp',
252 | count: true,
253 | limit: 50,
254 | }, options)
255 | });
256 |
257 | return {
258 | transfers: data.data,
259 | contractMap:data.contractMap,
260 | contractInfo:data.contractInfo,
261 | total: data.total,
262 | rangeTotal: data.rangeTotal,
263 | };
264 | }
265 |
266 | async getParticipateProject(address,options = {}) {
267 | let data = await xhr.get(`${this.apiUrl}/api/participate_project`,
268 | {
269 | params: Object.assign({
270 | address
271 | }, options)
272 | })
273 | return data
274 |
275 | }
276 |
277 | async getBlockByNumber(options = {}) {
278 | let {blocks} = await this.getBlocks(
279 | Object.assign(
280 | {limit: 1,},
281 | options
282 | )
283 | );
284 |
285 | return blocks[0];
286 | }
287 |
288 | async getBlockByHash(hash) {
289 | let {blocks} = await this.getBlocks({
290 | limit: 1,
291 | hash,
292 | });
293 |
294 | return blocks[0];
295 | }
296 |
297 | async getTransactionByHash(hash,options) {
298 | let {data} = await xhr.get(`${this.apiUrl}/api/transaction-info`,
299 | {
300 | params: Object.assign({
301 | hash
302 | }, options),
303 | })
304 | return data;
305 | }
306 |
307 |
308 | async getIssuedAsset(owner) {
309 | let {data} = await xhr.get(`${this.apiUrl}/api/token`, {
310 | params: {
311 | showAll: 1,
312 | owner: owner,
313 | },
314 | });
315 | return {
316 | token: data.data[0],
317 | data,
318 | };
319 | }
320 |
321 | async getAccounts(options = {}) {
322 | let {data} = await xhr.get(`${this.apiUrl}/api/account/list`, {
323 | params: Object.assign({
324 | sort: '-balance',
325 | limit: 50,
326 | }, options)
327 | });
328 |
329 | return {
330 | accounts: data.data,
331 | contractMap:data.contractMap,
332 | contractInfo:data.contractInfo,
333 | total: data.total,
334 | rangeTotal:data.rangeTotal,
335 | };
336 | }
337 |
338 | async getVotes(options = {}) {
339 | let {data} = await xhr.get(`${this.apiUrl}/api/vote`, {
340 | params: Object.assign({
341 | sort: '-timestamp',
342 | limit: 50,
343 | }, options)
344 | });
345 |
346 | return {
347 | votes: data.data,
348 | total: data.total,
349 | totalVotes: data.totalVotes,
350 | };
351 | }
352 |
353 | async secondsUntilNextCycle() {
354 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/next-cycle`);
355 | return data.nextCycle / 1000;
356 | }
357 |
358 |
359 | async getAccountByAddress(address) {
360 | let {data} = await xhr.get(`${this.apiUrl}/api/account/${address}`);
361 | return data;
362 | }
363 |
364 | async getRichList() {
365 | let {data} = await xhr.get(`${this.apiUrl}/api/account/richlist`);
366 | return data;
367 | }
368 |
369 | async getVotesForCurrentCycle() {
370 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/current-cycle`);
371 | return data;
372 | }
373 |
374 | async getVotesList() {
375 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/witness`)
376 | return data
377 | }
378 |
379 | async getLiveVotes() {
380 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/live`)
381 | return data.data;
382 | }
383 |
384 | async getTransferStats(options = {}) {
385 | let {data} = await xhr.get(`${this.apiUrl}/api/transfer/stats`, {
386 | params: Object.assign({}, options)
387 | });
388 |
389 | return {
390 | stats: data,
391 | };
392 | }
393 |
394 | async getBlockStats(options = {}) {
395 | let {data} = await xhr.get(`${this.apiUrl}/api/block/stats`, {
396 | params: Object.assign({}, options)
397 | });
398 |
399 | return {
400 | stats: data,
401 | };
402 | }
403 |
404 | async getAddress(address,options) {
405 | let {data} = await xhr.get(`${this.apiUrl}/api/accountv2`, {
406 | params: Object.assign({
407 | address,
408 | }, options)
409 | })
410 | return data;
411 | }
412 |
413 | async getAddressMedia(address) {
414 | let {data} = await xhr.get(`${this.apiUrl}/api/account/${address}/media`);
415 | return data;
416 | }
417 |
418 | async getAddressStats(address) {
419 | let {data} = await xhr.get(`${this.apiUrl}/api/account/stats?address=` + address);
420 | return data;
421 | }
422 |
423 | async getTokens(options = {}) {
424 | let {data} = await xhr.get(`${this.apiUrl}/api/token`, {
425 | params: Object.assign({
426 | sort: 'rank',
427 | limit: 50,
428 | }, options)
429 | });
430 |
431 | return {
432 | tokens: data.data,
433 | total: data.total,
434 | }
435 | }
436 |
437 | async getAccountVotes(address) {
438 | let {data} = await xhr.get(`${this.apiUrl}/api/account/votes?address=` + address);
439 | return data;
440 | }
441 |
442 | async getToken(name) {
443 | let {data} = await xhr.get(`${this.apiUrl}/api/token/${name}`);
444 | return data;
445 | }
446 |
447 | async getTokenHolders(name, options = {}) {
448 | let {data} = await xhr.get(`${this.apiUrl}/api/tokenholders`, {
449 | params: Object.assign({
450 | sort: '-balance',
451 | limit: 50,
452 | }, options)
453 | });
454 |
455 | return {
456 | addresses: data.data,
457 | total: data.total,
458 | rangeTotal:data.rangeTotal,
459 | contractMap:data.contractMap
460 | };
461 | }
462 |
463 | async getWitnesses() {
464 | let {data} = await xhr.get(`${this.apiUrl}/api/witness`);
465 |
466 | return {
467 | witnesses: data,
468 | total: data.length,
469 | };
470 | }
471 |
472 | async getNodeLocations() {
473 | let {data} = await xhr.get(`${this.apiUrl}/api/nodemap`);
474 |
475 | return {
476 | nodes: data,
477 | total: data.length,
478 | };
479 | }
480 |
481 | async getNodes() {
482 | let {data} = await xhr.get(`${this.apiUrl}/api/node`);
483 |
484 | return {
485 | nodes: data.nodes,
486 | total: data.nodes.length,
487 | status: data.status,
488 | };
489 | }
490 |
491 | async getAccountBalances(address) {
492 | let {data} = await xhr.get(`${this.apiUrl}/api/account/${address}/balance`);
493 | return data;
494 | }
495 |
496 | async getSystemStatus() {
497 | let {data} = await xhr.get(`${this.apiUrl}/api/system/status`);
498 | return data;
499 | }
500 |
501 | async getMarkets() {
502 | let {data} = await xhr.get(`${this.apiUrl}/api/market/markets`);
503 | return data;
504 | }
505 |
506 | async readTransaction(transactionHex) {
507 | let {data} = await xhr.post(`${this.apiUrl}/api/transaction?dry-run`, {
508 | transaction: transactionHex,
509 | });
510 | return data;
511 | }
512 |
513 | async readTransactionNew(transactionHex) {
514 | let {data} = await xhr.post(`${this.apiUrl}/api/transaction?dry-run=1`, {
515 | transaction: transactionHex,
516 | });
517 | return data;
518 | }
519 |
520 | async getVoteStats() {
521 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/stats`);
522 | return data.results;
523 | }
524 |
525 | async getTxOverviewStats() {
526 | let {data} = await xhr.get(`${this.apiUrl}/api/stats/overview`);
527 | return {
528 | txOverviewStats: data.data
529 | }
530 | }
531 |
532 | async getTxOverviewStatsAll(number) {
533 | let {data} = await xhr.get(`${this.apiUrl}/api/stats/overview?days=${number}`);
534 | return {
535 | txOverviewStats: data.data
536 | }
537 | }
538 |
539 | async getStatisticData() {
540 | let {data} = await xhr.get(`${this.apiUrl}/api/witness/maintenance-statistic`);
541 | return {
542 | statisticData: data
543 | }
544 | }
545 |
546 | async getVoteWitness(address) {
547 | let {data} = await xhr.get(`${this.apiUrl}/api/vote/witness?address=` + address);
548 | return data
549 | }
550 |
551 | async contractsVerify(verifyData) {
552 | let {data} = await xhr.post(`${this.apiUrl}/api/contracts/verify`, verifyData);
553 | return data;
554 | }
555 |
556 | async getContracts(options = {}) {
557 | let {data} = await xhr.get(`${this.apiUrl}/api/contracts`, {
558 | params: Object.assign({
559 | count: true,
560 | limit: 40,
561 | }, options)
562 | });
563 |
564 | return data;
565 | }
566 |
567 | async getContractTxs(options = {}) {
568 | let {data} = await xhr.get(`${this.apiUrl}/api/contracts/transaction`, {
569 | params: Object.assign({
570 | sort: '-timestamp',
571 | count: true,
572 | limit: 50,
573 | }, options)
574 | });
575 |
576 | return data;
577 | }
578 |
579 | async getContractOverview(address,options) {
580 | // let {data} = await xhr.get(`${this.apiUrl}/api/contract?contract=` + address);
581 | let {data} = await xhr.get(`${this.apiUrl}/api/contract`, {
582 | params: Object.assign({
583 | contract:address,
584 | }, options)
585 | })
586 | return data;
587 | }
588 |
589 | async getContractCode(address) {
590 | let {data} = await xhr.get(`${this.apiUrl}/api/contracts/code?contract=${address}`);
591 |
592 | return data;
593 | }
594 |
595 | async getContractEvent(address) {
596 | let {data} = await xhr.get(`${this.apiUrl}/api/contracts/event?contract=${address}`);
597 |
598 | return data;
599 | }
600 |
601 |
602 | async getContractTriggers(options = {}) {
603 | let {data} = await xhr.get(`${this.apiUrl}/api/contracts/trigger`, {
604 | params: Object.assign({
605 | sort: '-timestamp',
606 | confirm: 0,
607 | count: true,
608 | limit: 50,
609 | }, options)
610 | });
611 |
612 | return {
613 | triggers: data.data,
614 | contractInfo:data.contractInfo,
615 | contractMap:data.contractMap,
616 | total: data.total,
617 | rangeTotal:data.rangeTotal
618 | };
619 | }
620 |
621 | async getAccountByAddressNew(address) {
622 | let {data} = await xhr.get(`${this.apiUrl}/api/accountv2?address=` + address);
623 | return data;
624 | }
625 |
626 | async getExchangesList(options = {}) {
627 | let {data} = await xhr.get(`https://bancor.trx.market/api/exchanges/list`, {
628 | params: Object.assign({
629 | sort: '-balance',
630 | }, options)
631 | });
632 | return data;
633 | }
634 |
635 | async exchange(options = {}) {
636 | let {data} = await xhr.post(`${this.apiUrl}/api/exchange/transaction`, options);
637 | return data;
638 | }
639 |
640 | async getExchangesKline(options = {}) {
641 | let {data} = await xhr.get(`${this.apiUrl}/api/exchange/kgraph`, {
642 | params: options
643 | });
644 |
645 | return data
646 | }
647 |
648 |
649 | async getTransactionList(options = {}) {
650 | let {data} = await xhr.get(`${this.apiUrl}/api/exchange/transaction`, {
651 | params: Object.assign({
652 | sort: '-timestamp',
653 | start: 0,
654 | limit: 50,
655 | }, options)
656 | });
657 | return data
658 | }
659 |
660 | async getChainparameters() {
661 | let {data} = await xhr.get(`${this.apiUrl}/api/chainparameters`);
662 | return {
663 | tronParameters: data.tronParameters,
664 | }
665 | }
666 |
667 | async getProposalList(options = {}) {
668 | let {data} = await xhr.get(`${this.apiUrl}/api/proposal`, {
669 | params: Object.assign({
670 | sort: '-timestamp',
671 | limit: 50,
672 | }, options)
673 | });
674 | return {
675 | proposal: data.data,
676 | total: data.total
677 | }
678 | }
679 |
680 | async getProposalById(id) {
681 | let {data} = await xhr.get(`${this.apiUrl}/api/proposal?id=` + id);
682 | return {
683 | data: data
684 | }
685 | }
686 |
687 | async getHolderBalance(options = {}) {
688 | let {data} = await xhr.get(`${this.apiUrl}/api/token_trc20/holder_balance`, {
689 | params: options
690 | });
691 | return data
692 | }
693 |
694 | async getexchangesAllList(options = {}) {
695 | let {data} = await xhr.get(`${this.apiUrl}/api/exchanges/listall`, {
696 | params: options
697 | });
698 | return {
699 | exchangesAllList: data
700 | }
701 | }
702 |
703 | async getFundsSupply(options = {}) {
704 | let {data} = await xhr.get(`${this.apiUrl}/api/funds`, {
705 | params: options
706 | });
707 | return {
708 | funds: data
709 | }
710 | }
711 |
712 | async getBttFundsSupply(options = {}) {
713 | let {data} = await xhr.get(`${this.apiUrl}/api/bittorrent/fund`, {
714 | params: options
715 | });
716 | return {
717 | funds: data
718 | }
719 | }
720 |
721 | async getlistdonators(options = {}) {
722 | let {data} = await xhr.get(`${this.apiUrl}/api/listdonators`, {
723 | params: options
724 | });
725 | return {
726 | list: data
727 | }
728 | }
729 |
730 | async getNotices(options = {}) {
731 | let {data} = await xhr.get(`${this.apiUrl}/api/announcement`, {
732 | params: Object.assign({type: 1, start: 0, limit: 10, status: 0}, options)
733 | });
734 | return data
735 | }
736 |
737 |
738 | async getTRC20tfs(options = {}) {
739 | let {data} = await xhr.get(`${this.apiUrl}/api/contract/events`, {
740 | params: options
741 | });
742 |
743 | return {
744 | list: data.data,
745 | total: data.total,
746 | rangeTotal:data.rangeTotal,
747 | };
748 | }
749 |
750 | async getAddressTokens(options={}) {
751 | let {data} = await xhr.get(`${this.apiUrl}/api/account/tokens`, {
752 | params: options
753 | });
754 |
755 | return {
756 | data
757 | };
758 | }
759 |
760 | async getInternalTransaction(options = {}) {
761 | let {data} = await xhr.get(`${this.apiUrl}/api/internal-transaction`, {
762 | params: options
763 | });
764 |
765 | return {
766 | list: data.data,
767 | contractMap:data.contractMap,
768 | contractInfo:data.contractInfo,
769 | total: data.total,
770 | rangeTotal:data.rangeTotal,
771 | };
772 | }
773 |
774 | async getAssetTransfers(options = {}) {
775 | let {data} = await xhr.get(`${this.apiUrl}/api/asset/transfer`, {
776 | params: options
777 | });
778 |
779 | return {
780 | list: data.Data,
781 | total: data.total,
782 | rangeTotal:data.rangeTotal,
783 | };
784 | }
785 |
786 | async getTokenTRC20Transfers(options = {}) {
787 | let {data} = await xhr.get(`${this.apiUrl}/api/token_trc20/transfers`, {
788 | params: options
789 | });
790 |
791 | return {
792 | list: data.token_transfers,
793 | contractInfo:data.contractInfo,
794 | total: data.total,
795 | rangeTotal:data.rangeTotal,
796 | };
797 | }
798 |
799 | async getTransfersAll(options = {}) {
800 | let {data} = await xhr.get(`${this.apiUrl}/api/trc10trc20-transfer`, {
801 | params: Object.assign({
802 | sort: '-timestamp',
803 | count: true,
804 | limit: 50,
805 | }, options)
806 | });
807 |
808 | return {
809 | transfers: data.transfers,
810 | contractMap:data.contractMap,
811 | total: data.total,
812 | rangeTotal: data.rangeTotal,
813 | };
814 | }
815 |
816 | async getContractInfo(address) {
817 | let {data} = await xhr.get(`${this.apiUrl}/api/contract?contract=${address}`);
818 | return data;
819 | }
820 |
821 | async createToken20(options = {}) {
822 | let {data} = await xhr.post(`${this.apiUrl}/external/trc20tokens`, options);
823 | return data;
824 | }
825 |
826 | async createToken1155(options = {}) {
827 | let {data} = await xhr.post(`${this.apiUrl}/external/trc1155tokens`, options);
828 | return data;
829 | }
830 |
831 | async createToken721(options = {}) {
832 | let {data} = await xhr.post(`${this.apiUrl}/external/trc721tokens`, options);
833 | return data;
834 | }
835 |
836 | async updateToken721(options = {}) {
837 | let {data} = await xhr.post(`${this.apiUrl}/external/trc721tokens/update`, options);
838 | return data;
839 | }
840 |
841 | async updateToken1155(options = {}) {
842 | let {data} = await xhr.post(`${this.apiUrl}/external/trc1155tokens/update`, options);
843 | return data;
844 | }
845 |
846 | async updateToken20(options = {}) {
847 | let {data} = await xhr.post(`${this.apiUrl}/external/trc20tokens/update`, options);
848 | return data;
849 | }
850 |
851 | async updateToken10(options = {}) {
852 | let {data} = await xhr.post(`${this.apiUrl}/external/trc10tokens/update`, options);
853 | return data;
854 | }
855 |
856 |
857 | async getTps(time) {
858 | let {data} = await xhr.get(`${this.apiUrl}/api/system/tps?time=${time}`);
859 | return data;
860 | }
861 |
862 | async getTagNameList() {
863 | return [
864 | { name: 'binance', addressList: {
865 | Cold: ['TMuA6YqfCeX8EhbfYEg5y7S4DqzSJireY9', 'TWd4WrZ9wn84f5x1hZhL4DHvk738ns5jwb'],
866 | Hot: ['TAUN6FwrnwwmaEqYcckffC7wYmbaS6cBiX']}
867 | },{
868 | name: 'Upbit', addressList: {
869 | Hot: ['TDU1uJNxDND9zhzYjnn7ZunHj18jw7oAca']
870 | }
871 | },{
872 | name: 'Okex', addressList: {
873 | default: ['TM1zzNDZD2DPASbKcgdVoTYhfmYgtfwx9R','TS1P2y41FEaxvNNktvriTbjKHpQPKoRvic']
874 | }
875 | },{
876 | name: 'Huobi', addressList: {
877 | default: ['TNaRAoLUyYEV2uF7GUrzSjRQTU8v5ZJ5VR']
878 | }
879 | },{
880 | name: 'Bittrex', addressList: {
881 | Hot: ['TAahLbGTZk6YuCycii72datPQEtyC5x231'],
882 | default: ['TA5vCXk4f1SrCMfz361UxUNABRGP1g2F1r']
883 | }
884 | },{
885 | name: 'Kucoin', addressList: {
886 | default: ['TLWE45u7eusdewSDCjZqUNmyhTUL1NBMzo','TBcUJq55x7Q83ZSr2AqWj59TRj2LvxVr8a']
887 | }
888 | },{
889 | name: 'Gate', addressList: {
890 | default: ['TBA6CypYJizwA9XdC7Ubgc5F1bxrQ7SqPt']
891 | }
892 | },{
893 | name: 'poloniex', addressList: {
894 | default: ['TNCmcTdyrYKMtmE1KU2itzeCX76jGm5Not']
895 | }
896 | },
897 | {
898 | name: 'bitfinex', addressList: {
899 | default: ['TXFBqBbqJommqZf7BV8NNYzePh97UmJodJ']
900 | }
901 | }
902 | ];
903 | }
904 | async getCountByType(params) {
905 | let {data} = await xhr.get(`${this.apiUrl}/api/count`,{params});
906 | return data;
907 | }
908 |
909 | async getUserList(params) {
910 | let {data} = await xhr.post(`https://tronscan.org/users/getUserList`, params);
911 |
912 | return {
913 | data: data.data,
914 | total: data.total,
915 | };
916 | }
917 | async getAddressReward(params) {
918 | let {data} = await xhr.get(`${this.apiUrl}/api/address/reward`,{params});
919 | return data;
920 | }
921 |
922 | getTriggerSmartContractHexStr(value) {
923 | let hexStr = buildTriggerSmartContract(value);
924 | return hexStr;
925 | }
926 |
927 | getParameterValue (hexStr,ContractType){
928 | let hexStrBytes = hexStr2byteArray(hexStr);
929 | let parameterValue;
930 | let parameter = {};
931 | switch (ContractType) {
932 | case "TransferContract": {
933 | parameterValue = getTransferContractParameterValue(hexStrBytes)
934 | return parameterValue;
935 | }
936 | case "TransferAssetContract": {
937 | parameterValue = getTransferAssetContractParameterValue(hexStrBytes)
938 | return parameterValue;
939 | }
940 | case "TriggerSmartContract": {
941 | parameterValue = getTriggerSmartContractParameterValue(hexStrBytes)
942 | for(let i in parameterValue){
943 | if(parameterValue[i] !== ''){
944 | parameter[i] = parameterValue[i]
945 | }
946 | }
947 | return parameter;
948 | }
949 | case "AccountPermissionUpdateContract": {
950 | // let contractData = await xhr.post(`https://tronexapi.tronscan.org/api/contract/convert`, {
951 | // "outType":"json",
952 | // "data":hexStr,
953 | // "contractType":ContractType
954 | // });
955 | // parameterValue = contractData.data.message
956 | parameterValue = getAccountPermissionUpdateContractParameterValue(hexStrBytes)
957 | for(let i in parameterValue){
958 | if(parameterValue[i] !== ''){
959 | parameter[i] = parameterValue[i]
960 | }
961 | }
962 | return parameter;
963 | }
964 |
965 | }
966 |
967 |
968 |
969 | }
970 |
971 | /*
972 | * get account token list
973 | */
974 | async getAccountWallet(params) {
975 | let {data} = await xhr.get(`${this.apiUrl}/api/account/wallet`,{params});
976 | return data;
977 | }
978 |
979 | /*
980 | * get search token
981 | */
982 | async getAccountTokenSearch(params) {
983 | let {data} = await xhr.get(`${this.apiUrl}/api/token/search`,{params});
984 | return data;
985 | }
986 |
987 | /*
988 | ** account add show token list
989 | */
990 | async getAccountAddShowList(params) {
991 | let {data} = await xhr.post(`${this.apiUrl}/external/account/addShowList`,params);
992 | return data;
993 | }
994 |
995 |
996 | /*
997 | ** account add show block list
998 | */
999 | async getAccountAddBlockList(params) {
1000 | let {data} = await xhr.post(`${this.apiUrl}/external/account/addBlockList`,params);
1001 | return data;
1002 | }
1003 |
1004 | /*
1005 | ** tvc total value on chain
1006 | */
1007 | async getTVCData(params) {
1008 | let {data} = await xhr.get(`${this.apiUrl}/api/tokenTvc`,{params});
1009 | return data;
1010 | }
1011 |
1012 | /*
1013 | * get account token list
1014 | */
1015 | async getAccountWallet(params) {
1016 | let {data} = await xhr.get(`${this.apiUrl}/api/account/wallet`,{params});
1017 | return data;
1018 | }
1019 |
1020 | /*
1021 | * get search token
1022 | */
1023 | async getAccountTokenSearch(params) {
1024 | let {data} = await xhr.get(`${this.apiUrl}/api/token/search`,{params});
1025 | return data;
1026 | }
1027 |
1028 | /*
1029 | ** account add show token list
1030 | */
1031 | async getAccountAddShowList(params) {
1032 | let {data} = await xhr.post(`${this.apiUrl}/external/account/addShowList`,params);
1033 | return data;
1034 | }
1035 |
1036 |
1037 | /*
1038 | ** account add show block list
1039 | */
1040 | async getAccountAddBlockList(params) {
1041 | let {data} = await xhr.post(`${this.apiUrl}/external/account/addBlockList`,params);
1042 | return data;
1043 | }
1044 |
1045 |
1046 | }
1047 |
1048 | module.exports = ApiClient;
1049 |
--------------------------------------------------------------------------------
/src/config.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 |
3 | module.exports = {
4 | PROTO_PATH: path.resolve(__dirname, "../protocol/api"),
5 | };
6 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | const Client = require("./client/http");
2 |
3 | module.exports = {
4 | Client,
5 | };
6 |
--------------------------------------------------------------------------------
/src/lib/base58.js:
--------------------------------------------------------------------------------
1 | var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
2 | var ALPHABET_MAP = {}
3 | for(var i = 0; i < ALPHABET.length; i++) {
4 | ALPHABET_MAP[ALPHABET.charAt(i)] = i
5 | }
6 | var BASE = 58;
7 |
8 | /**
9 | *
10 | * @param buffer
11 | * @returns {string}
12 | */
13 | function encode58(buffer) {
14 | if (buffer.length === 0) return '';
15 |
16 | var i, j, digits = [0];
17 | for (i = 0; i < buffer.length; i++) {
18 | for (j = 0; j < digits.length; j++) digits[j] <<= 8
19 |
20 | digits[0] += buffer[i];
21 |
22 | var carry = 0;
23 | for (j = 0; j < digits.length; ++j) {
24 | digits[j] += carry;
25 |
26 | carry = (digits[j] / BASE) | 0;
27 | digits[j] %= BASE
28 | }
29 |
30 | while (carry) {
31 | digits.push(carry % BASE);
32 |
33 | carry = (carry / BASE) | 0
34 | }
35 | }
36 |
37 | // deal with leading zeros
38 | for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0)
39 |
40 | return digits.reverse().map(function(digit) { return ALPHABET[digit] }).join('');
41 | }
42 |
43 | /**
44 | * @param string
45 | * @returns number[]
46 | */
47 | function decode58(string) {
48 | if (string.length === 0) return []
49 |
50 | var i, j, bytes = [0]
51 | for (i = 0; i < string.length; i++) {
52 | var c = string[i]
53 | if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character')
54 |
55 | for (j = 0; j < bytes.length; j++) bytes[j] *= BASE
56 | bytes[0] += ALPHABET_MAP[c]
57 |
58 | var carry = 0
59 | for (j = 0; j < bytes.length; ++j) {
60 | bytes[j] += carry
61 |
62 | carry = bytes[j] >> 8
63 | bytes[j] &= 0xff
64 | }
65 |
66 | while (carry) {
67 | bytes.push(carry & 0xff)
68 |
69 | carry >>= 8
70 | }
71 | }
72 |
73 | // deal with leading zeros
74 | for (i = 0; string[i] === '1' && i < string.length - 1; i++) {
75 | bytes.push(0)
76 | }
77 |
78 | return bytes.reverse();
79 | }
80 |
81 | module.exports = {
82 | encode58,
83 | decode58,
84 | };
85 |
--------------------------------------------------------------------------------
/src/lib/code.js:
--------------------------------------------------------------------------------
1 | const btoa = require('btoa');
2 |
3 | /* eslint-disable */
4 | function bin2String(array) {
5 | return String.fromCharCode.apply(String, array);
6 | }
7 |
8 | //Compare two byteArray to see if they are equal
9 | function arrayEquals(array1, array2) {
10 | if (array1.length != array2.length) {
11 | return false;
12 | }
13 | var i;
14 | for (i = 0; i < array1.length; i++) {
15 | if (array1[i] != array2[i]) {
16 | return false;
17 | }
18 | }
19 | return true;
20 | }
21 |
22 | //Parsing TransAction objects from base64 strings
23 | function getTransActionFromBase64String(base64String) {
24 | var bytesDecode = base64DecodeFromString(base64String);
25 | var transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode);
26 | //ToDo : ret is success
27 | return transaction;
28 | }
29 |
30 | //Return a list contains contract object
31 | //Get the list of contracts from the TransAction object
32 | function getContractListFromTransaction(transaction) {
33 | var raw = transaction.getRawData();
34 | var type = raw.getType();
35 | if (type != 1) {
36 | layer.alert("Invalid transaction type !!!!" + type);
37 | return null;
38 | }
39 | var contractList = raw.getContractList();
40 | var count = contractList.length;
41 | if (count == 0) {
42 | layer.alert("No contract !!!!");
43 | return null;
44 | }
45 |
46 | array = new Array(count);
47 | var unpack = proto.google.protobuf.Any.prototype.unpack;
48 | while (count > 0) {
49 | count--;
50 | var oneContract = contractList[count];
51 | var any = oneContract.getParameter();
52 | var contarcType = oneContract.getType();
53 | var obje;
54 | switch (contarcType) {
55 | case proto.protocol.Transaction.Contract.ContractType.ACCOUNTCREATECONTRACT:
56 | obje = any.unpack(
57 | proto.protocol.AccountCreateContract.deserializeBinary,
58 | "protocol.AccountCreateContract");
59 | break;
60 |
61 | case proto.protocol.Transaction.Contract.ContractType.TRANSFERCONTRACT:
62 | obje = any.unpack(
63 | proto.protocol.TransferContract.deserializeBinary,
64 | "protocol.TransferContract");
65 | break;
66 |
67 | case proto.protocol.Transaction.Contract.ContractType.TRANSFERASSETCONTRACT:
68 | obje = any.unpack(
69 | proto.protocol.TransferAsstContract.deserializeBinary,
70 | "protocol.TransferAssetContract");
71 | break;
72 |
73 | case proto.protocol.Transaction.Contract.ContractType.VOTEASSETCONTRACT:
74 | obje = any.unpack(
75 | proto.protocol.VoteAssetContract.deserializeBinary,
76 | "protocol.VoteAssetContract");
77 | break;
78 |
79 | case proto.protocol.Transaction.Contract.ContractType.VOTEWITNESSCONTRACT:
80 | obje = any.unpack(
81 | proto.protocol.VoteWitnessContract.deserializeBinary,
82 | "protocol.VoteWitnessContract");
83 | break;
84 |
85 | case proto.protocol.Transaction.Contract.ContractType.WITNESSCREATECONTRACT:
86 | obje = any.unpack(
87 | proto.protocol.WitnessCreateContract.deserializeBinary,
88 | "protocol.WitnessCreateContract");
89 | break;
90 |
91 | case proto.protocol.Transaction.Contract.ContractType.ASSETISSUECONTRACT:
92 | obje = any.unpack(
93 | proto.protocol.AssetIssueContract.deserializeBinary,
94 | "protocol.AssetIssueContract");
95 | break;
96 |
97 | case proto.protocol.Transaction.Contract.ContractType.DEPLOYCONTRACT:
98 | obje = any.unpack(
99 | proto.protocol.DeployContract.deserializeBinary,
100 | "protocol.DeployContract");
101 | break;
102 |
103 | case proto.protocol.Transaction.Contract.ContractType.WITNESSUPDATECONTRACT:
104 | obje = any.unpack(
105 | proto.protocol.WitnessUpdateContract.deserializeBinary,
106 | "protocol.WitnessUpdateContract");
107 | break;
108 | }
109 | array[count] = obje;
110 | }
111 | return array;
112 | }
113 |
114 | //String to byteArray data format
115 | function stringToBytes(str) {
116 | var bytes = new Array();
117 | var len, c;
118 | len = str.length;
119 | for (var i = 0; i < len; i++) {
120 | c = str.charCodeAt(i);
121 | if (c >= 0x010000 && c <= 0x10FFFF) {
122 | bytes.push(((c >> 18) & 0x07) | 0xF0);
123 | bytes.push(((c >> 12) & 0x3F) | 0x80);
124 | bytes.push(((c >> 6) & 0x3F) | 0x80);
125 | bytes.push((c & 0x3F) | 0x80);
126 | } else if (c >= 0x000800 && c <= 0x00FFFF) {
127 | bytes.push(((c >> 12) & 0x0F) | 0xE0);
128 | bytes.push(((c >> 6) & 0x3F) | 0x80);
129 | bytes.push((c & 0x3F) | 0x80);
130 | } else if (c >= 0x000080 && c <= 0x0007FF) {
131 | bytes.push(((c >> 6) & 0x1F) | 0xC0);
132 | bytes.push((c & 0x3F) | 0x80);
133 | } else {
134 | bytes.push(c & 0xFF);
135 | }
136 | }
137 | return bytes;
138 |
139 | }
140 |
141 | //byteArray data format to string
142 | function bytesToString(arr) {
143 | if (typeof arr === 'string') {
144 | return arr;
145 | }
146 | var str = '',
147 | _arr = arr;
148 | for (var i = 0; i < _arr.length; i++) {
149 | var one = _arr[i].toString(2),
150 | v = one.match(/^1+?(?=0)/);
151 | if (v && one.length == 8) {
152 | var bytesLength = v[0].length;
153 | var store = _arr[i].toString(2).slice(7 - bytesLength);
154 | for (var st = 1; st < bytesLength; st++) {
155 | store += _arr[st + i].toString(2).slice(2);
156 | }
157 | str += String.fromCharCode(parseInt(store, 2));
158 | i += bytesLength - 1;
159 | } else {
160 | str += String.fromCharCode(_arr[i]);
161 | }
162 | }
163 | return str;
164 | }
165 |
166 | function hextoString(hex) {
167 | var arr = hex.split("")
168 | var out = ""
169 | for (var i = 0; i < arr.length / 2; i++) {
170 | var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
171 | var charValue = String.fromCharCode(tmp);
172 | out += charValue
173 | }
174 | return out
175 | }
176 |
177 | /* Convert a hex char to value */
178 | function hexChar2byte(c) {
179 | var d = 0;
180 | if (c >= 'A' && c <= 'F') {
181 | d = c.charCodeAt(0) - 'A'.charCodeAt(0) + 10;
182 | }
183 | else if (c >= 'a' && c <= 'f') {
184 | d = c.charCodeAt(0) - 'a'.charCodeAt(0) + 10;
185 | }
186 | else if (c >= '0' && c <= '9') {
187 | d = c.charCodeAt(0) - '0'.charCodeAt(0);
188 | }
189 | return d;
190 | }
191 |
192 | /* Check if a char is hex char */
193 | function isHexChar(c) {
194 | if ((c >= 'A' && c <= 'F') ||
195 | (c >= 'a' && c <= 'f') ||
196 | (c >= '0' && c <= '9')) {
197 | return 1;
198 | }
199 | return 0;
200 | }
201 |
202 | /* Convert HEX string to byte array */
203 |
204 | //16进制的ASCII字符串转为byteArray格式。
205 | function hexStr2byteArray(str) {
206 | var byteArray = Array();
207 | var d = 0;
208 | var j = 0;
209 | var k = 0;
210 |
211 | for (let i = 0; i < str.length; i++) {
212 | var c = str.charAt(i);
213 | if (isHexChar(c)) {
214 | d <<= 4;
215 | d += hexChar2byte(c);
216 | j++;
217 | if (0 === (j % 2)) {
218 | byteArray[k++] = d;
219 | d = 0;
220 | }
221 | }
222 | }
223 | return byteArray;
224 | }
225 |
226 |
227 | /* Convert a byte to string */
228 | function byte2hexStr(byte) {
229 | var hexByteMap = "0123456789ABCDEF";
230 | var str = "";
231 | str += hexByteMap.charAt(byte >> 4);
232 | str += hexByteMap.charAt(byte & 0x0f);
233 | return str;
234 | }
235 |
236 | /* Convert byte arry to HEX string */
237 |
238 | //Convert byteArray format data to hexadecimal ASCII string
239 | function byteArray2hexStr(byteArray) {
240 | var str = "";
241 | for (var i = 0; i < (byteArray.length - 1); i++) {
242 | str += byte2hexStr(byteArray[i]);
243 | }
244 | str += byte2hexStr(byteArray[i]);
245 | return str;
246 | }
247 |
248 | //Decode the original text from the base64 string in byteArray format
249 | function base64DecodeFromString(string64) {
250 | var b = new Base64();
251 | var decodeBytes = b.decodeToByteArray(string64);
252 | return decodeBytes;
253 | }
254 |
255 | //return baset64 String
256 | //Encode byteArray format data to base64 string
257 | function base64EncodeToString(bytes) {
258 | // var string = bytesToString(bytes);
259 | var b = new Base64();
260 | var string64 = b.encodeIgnoreUtf8(bytes);
261 | return string64
262 | }
263 |
264 | function Base64() {
265 |
266 | // private property
267 | let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
268 |
269 | // public method for encoding
270 | this.encode = function (input) {
271 | var output = "";
272 | var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
273 | var i = 0;
274 | // input = _utf8_encode(input);
275 | while (i < input.length) {
276 | chr1 = input.charCodeAt(i++);
277 | chr2 = input.charCodeAt(i++);
278 | chr3 = input.charCodeAt(i++);
279 | enc1 = chr1 >> 2;
280 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
281 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
282 | enc4 = chr3 & 63;
283 | if (isNaN(chr2)) {
284 | enc3 = enc4 = 64;
285 | } else if (isNaN(chr3)) {
286 | enc4 = 64;
287 | }
288 | output = output +
289 | _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
290 | _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
291 | }
292 | return output;
293 | }
294 |
295 | // public method for encoding
296 | this.encodeIgnoreUtf8 = function (inputBytes) {
297 | var output = "";
298 | var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
299 | var i = 0;
300 | // input = _utf8_encode(input);
301 | while (i < inputBytes.length) {
302 | chr1 = inputBytes[i++];
303 | chr2 = inputBytes[i++];
304 | chr3 = inputBytes[i++];
305 | enc1 = chr1 >> 2;
306 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
307 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
308 | enc4 = chr3 & 63;
309 | if (isNaN(chr2)) {
310 | enc3 = enc4 = 64;
311 | } else if (isNaN(chr3)) {
312 | enc4 = 64;
313 | }
314 | output = output +
315 | _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
316 | _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
317 | }
318 | return output;
319 | }
320 |
321 | // public method for decoding
322 | this.decode = function (input) {
323 | var output = "";
324 | var chr1, chr2, chr3;
325 | var enc1, enc2, enc3, enc4;
326 | var i = 0;
327 | input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
328 | while (i < input.length) {
329 | enc1 = _keyStr.indexOf(input.charAt(i++));
330 | enc2 = _keyStr.indexOf(input.charAt(i++));
331 | enc3 = _keyStr.indexOf(input.charAt(i++));
332 | enc4 = _keyStr.indexOf(input.charAt(i++));
333 | chr1 = (enc1 << 2) | (enc2 >> 4);
334 | chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
335 | chr3 = ((enc3 & 3) << 6) | enc4;
336 | output = output + String.fromCharCode(chr1);
337 | if (enc3 != 64) {
338 | output = output + String.fromCharCode(chr2);
339 | }
340 | if (enc4 != 64) {
341 | output = output + String.fromCharCode(chr3);
342 | }
343 | }
344 | output = this._utf8_decode(output);
345 | return output;
346 | }
347 |
348 | // public method for decoding
349 | this.decodeToByteArray = function (input) {
350 | var output = "";
351 | var chr1, chr2, chr3;
352 | var enc1, enc2, enc3, enc4;
353 | var i = 0;
354 | input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
355 | while (i < input.length) {
356 | enc1 = _keyStr.indexOf(input.charAt(i++));
357 | enc2 = _keyStr.indexOf(input.charAt(i++));
358 | enc3 = _keyStr.indexOf(input.charAt(i++));
359 | enc4 = _keyStr.indexOf(input.charAt(i++));
360 | chr1 = (enc1 << 2) | (enc2 >> 4);
361 | chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
362 | chr3 = ((enc3 & 3) << 6) | enc4;
363 | output = output + String.fromCharCode(chr1);
364 | if (enc3 != 64) {
365 | output = output + String.fromCharCode(chr2);
366 | }
367 | if (enc4 != 64) {
368 | output = output + String.fromCharCode(chr3);
369 | }
370 | }
371 | var outBytes = this._out2ByteArray(output);
372 | return outBytes;
373 | };
374 |
375 | // private method for UTF-8 decoding
376 | this._out2ByteArray = function (utftext) {
377 | let byteArray = new Array(utftext.length)
378 | let i = 0;
379 | let c = 0;
380 | let c1 = 0;
381 | let c2 = 0;
382 | while (i < utftext.length) {
383 | c = utftext.charCodeAt(i);
384 | byteArray[i] = c;
385 | i++;
386 | }
387 | return byteArray;
388 | };
389 |
390 | // private method for UTF-8 encoding
391 | this._utf8_encode = function (string) {
392 | string = string.replace(/\r\n/g, "\n");
393 | var utftext = "";
394 | for (var n = 0; n < string.length; n++) {
395 | var c = string.charCodeAt(n);
396 | if (c < 128) {
397 | utftext += String.fromCharCode(c);
398 | } else if ((c > 127) && (c < 2048)) {
399 | utftext += String.fromCharCode((c >> 6) | 192);
400 | utftext += String.fromCharCode((c & 63) | 128);
401 | } else {
402 | utftext += String.fromCharCode((c >> 12) | 224);
403 | utftext += String.fromCharCode(((c >> 6) & 63) | 128);
404 | utftext += String.fromCharCode((c & 63) | 128);
405 | }
406 |
407 | }
408 | return utftext;
409 | }
410 |
411 | // private method for UTF-8 decoding
412 | this._utf8_decode = function (utftext) {
413 | var string = "";
414 | var i = 0;
415 | var c = c1 = c2 = 0;
416 | while (i < utftext.length) {
417 | c = utftext.charCodeAt(i);
418 | if (c < 128) {
419 | string += String.fromCharCode(c);
420 | i++;
421 | } else if ((c > 191) && (c < 224)) {
422 | c2 = utftext.charCodeAt(i + 1);
423 | string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
424 | i += 2;
425 | } else {
426 | c2 = utftext.charCodeAt(i + 1);
427 | c3 = utftext.charCodeAt(i + 2);
428 | string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3
429 | & 63));
430 | i += 3;
431 | }
432 | }
433 | return string;
434 | }
435 | }
436 |
437 | //yyyy-MM-DD HH-mm-ss
438 | function strToDate(str) {
439 | var tempStrs = str.split(" ");
440 | var dateStrs = tempStrs[0].split("-");
441 | var year = parseInt(dateStrs[0], 10);
442 | var month = parseInt(dateStrs[1], 10) - 1;
443 | var day = parseInt(dateStrs[2], 10);
444 | if (tempStrs.length > 1) {
445 | var timeStrs = tempStrs[1].split("-");
446 | var hour = parseInt(timeStrs [0], 10);
447 | var minute = parseInt(timeStrs[1], 10) - 1;
448 | var second = parseInt(timeStrs[2], 10);
449 | return new Date(year, month, day, hour, minute, second);
450 | }
451 |
452 | return new Date(year, month, day);
453 | }
454 |
455 | function isNumber(c) {
456 | if (c >= '0' && c <= '9') {
457 | return 1;
458 | }
459 | return 0;
460 | }
461 |
462 | //return 1: address --- 20Bytes HexString
463 | //return 2: blockNumber ------ Decimal number
464 | //return 3: assetName ------ String
465 | //return other: error
466 | function getStringType(str) {
467 | if (null == str) {
468 | return -1;
469 | }
470 |
471 | if (typeof(str) != 'string') {
472 | return -1;
473 | }
474 |
475 | if (str.length == 0 || str == "") {
476 | return -1;
477 | }
478 |
479 | var i = 0;
480 | if (str.length == 40) {
481 | for (; i < 40; i++) {
482 | var c = str.charAt(i);
483 | if (!isHexChar(c)) {
484 | break;
485 | }
486 | }
487 | }
488 | if (i == 40) {
489 | return 1; //40 Hex, Address
490 | }
491 |
492 | for (i = 0; i < str.length; i++) {
493 | var c = str.charAt(i);
494 | if (!isNumber(c)) {
495 | break;
496 | }
497 | }
498 | if (i == str.length) {
499 | return 2; //Alll Decimal number, BlockNumber
500 | }
501 |
502 | for (i = 0; i < str.length; i++) {
503 | var c = str.charAt(i);
504 | if (c > ' ') {
505 | return 3; //At least one visible character
506 | }
507 | }
508 |
509 | return -1;
510 | }
511 |
512 | function encodeString(str) {
513 | return Uint8Array.from(base64DecodeFromString(btoa(str)));
514 | }
515 | function encodeString2(str){
516 | return base64DecodeFromString(btoa(str));
517 | }
518 |
519 | module.exports = {
520 | base64EncodeToString,
521 | base64DecodeFromString,
522 | hexStr2byteArray,
523 | stringToBytes,
524 | encodeString,
525 | encodeString2
526 | };
527 |
--------------------------------------------------------------------------------
/src/lib/sha.js:
--------------------------------------------------------------------------------
1 | /*
2 | A JavaScript implementation of the SHA family of hashes, as
3 | defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding
4 | HMAC implementation as defined in FIPS PUB 198a
5 |
6 | Copyright Brian Turek 2008-2017
7 | Distributed under the BSD License
8 | See http://caligatio.github.com/jsSHA/ for more information
9 |
10 | Several functions taken from Paul Johnston
11 | */
12 | 'use strict';
13 | (function (Y) {
14 | function C(c, a, b) {
15 | var e = 0, h = [], n = 0, g, l, d, f, m, q, u, r, I = !1, v = [], w = [], t,
16 | y = !1, z = !1, x = -1;
17 | b = b || {};
18 | g = b.encoding || "UTF8";
19 | t = b.numRounds || 1;
20 | if (t !== parseInt(t, 10) || 1 > t) {
21 | throw Error(
22 | "numRounds must a integer >= 1");
23 | }
24 | if ("SHA-1" === c) {
25 | m = 512, q = K, u = Z, f = 160, r = function (a) {
26 | return a.slice()
27 | };
28 | } else if (0 === c.lastIndexOf("SHA-", 0)) {
29 | if (q = function (a, b) {
30 | return L(a, b, c)
31 | }, u = function (a, b, h, e) {
32 | var k, f;
33 | if ("SHA-224" === c || "SHA-256" === c) {
34 | k = (b + 65 >>> 9 << 4)
35 | + 15, f = 16;
36 | } else if ("SHA-384" === c || "SHA-512" === c) {
37 | k = (b
38 | + 129 >>> 10 <<
39 | 5) + 31, f = 32;
40 | } else {
41 | throw Error(
42 | "Unexpected error in SHA-2 implementation");
43 | }
44 | for (; a.length <= k;) {
45 | a.push(0);
46 | }
47 | a[b >>> 5] |= 128 << 24 - b % 32;
48 | b = b + h;
49 | a[k] = b & 4294967295;
50 | a[k - 1] = b / 4294967296 | 0;
51 | h = a.length;
52 | for (b = 0; b < h; b += f) {
53 | e = L(a.slice(b, b + f), e, c);
54 | }
55 | if ("SHA-224" === c) {
56 | a = [e[0], e[1], e[2], e[3], e[4], e[5],
57 | e[6]];
58 | } else if ("SHA-256" === c) {
59 | a = e;
60 | } else if ("SHA-384"
61 | === c) {
62 | a = [e[0].a, e[0].b, e[1].a, e[1].b, e[2].a, e[2].b,
63 | e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b];
64 | } else if ("SHA-512"
65 | === c) {
66 | a = [e[0].a, e[0].b, e[1].a, e[1].b, e[2].a, e[2].b,
67 | e[3].a, e[3].b, e[4].a,
68 | e[4].b, e[5].a, e[5].b, e[6].a, e[6].b, e[7].a,
69 | e[7].b];
70 | } else {
71 | throw Error(
72 | "Unexpected error in SHA-2 implementation");
73 | }
74 | return a
75 | }, r = function (a) {
76 | return a.slice()
77 | }, "SHA-224" === c) {
78 | m = 512, f = 224;
79 | } else if ("SHA-256"
80 | === c) {
81 | m = 512, f = 256;
82 | } else if ("SHA-384"
83 | === c) {
84 | m = 1024, f = 384;
85 | } else if ("SHA-512"
86 | === c) {
87 | m = 1024, f = 512;
88 | } else {
89 | throw Error(
90 | "Chosen SHA variant is not supported");
91 | }
92 | } else if (0 === c.lastIndexOf(
93 | "SHA3-", 0) || 0 === c.lastIndexOf("SHAKE", 0)) {
94 | var F = 6;
95 | q = D;
96 | r = function (a) {
97 | var c = [], e;
98 | for (e = 0; 5 > e; e += 1) {
99 | c[e] = a[e].slice();
100 | }
101 | return c
102 | };
103 | x = 1;
104 | if ("SHA3-224" ===
105 | c) {
106 | m = 1152, f = 224;
107 | } else if ("SHA3-256"
108 | === c) {
109 | m = 1088, f = 256;
110 | } else if ("SHA3-384"
111 | === c) {
112 | m = 832, f = 384;
113 | } else if ("SHA3-512"
114 | === c) {
115 | m = 576, f = 512;
116 | } else if ("SHAKE128"
117 | === c) {
118 | m = 1344, f = -1, F = 31, z = !0;
119 | } else if ("SHAKE256"
120 | === c) {
121 | m = 1088, f = -1, F = 31, z = !0;
122 | } else {
123 | throw Error(
124 | "Chosen SHA variant is not supported");
125 | }
126 | u = function (a, c, e, b, h) {
127 | e = m;
128 | var k = F, f, g = [], n = e >>> 5, l = 0, d = c >>> 5;
129 | for (f = 0; f < d && c >= e; f += n) {
130 | b = D(a.slice(f, f + n),
131 | b), c -= e;
132 | }
133 | a = a.slice(f);
134 | for (c %= e; a.length < n;) {
135 | a.push(0);
136 | }
137 | f = c >>> 3;
138 | a[f >> 2] ^= k << f % 4 * 8;
139 | a[n - 1] ^= 2147483648;
140 | for (b = D(a, b); 32 * g.length < h;) {
141 | a = b[l %
142 | 5][l / 5 | 0];
143 | g.push(a.b);
144 | if (32 * g.length >= h) {
145 | break;
146 | }
147 | g.push(a.a);
148 | l += 1;
149 | 0 === 64 * l % e && D(null, b)
150 | }
151 | return g
152 | }
153 | } else {
154 | throw Error("Chosen SHA variant is not supported");
155 | }
156 | d = M(a, g, x);
157 | l = A(c);
158 | this.setHMACKey = function (a, b, h) {
159 | var k;
160 | if (!0 === I) {
161 | throw Error("HMAC key already set");
162 | }
163 | if (!0 === y) {
164 | throw Error("Cannot set HMAC key after calling update");
165 | }
166 | if (!0 === z) {
167 | throw Error("SHAKE is not supported for HMAC");
168 | }
169 | g = (h || {}).encoding || "UTF8";
170 | b = M(b, g, x)(a);
171 | a = b.binLen;
172 | b = b.value;
173 | k = m >>> 3;
174 | h = k / 4 - 1;
175 | if (k < a / 8) {
176 | for (b = u(b, a, 0, A(c), f); b.length <= h;) {
177 | b.push(0);
178 | }
179 | b[h] &= 4294967040
180 | } else if (k > a / 8) {
181 | for (; b.length <= h;) {
182 | b.push(0);
183 | }
184 | b[h] &= 4294967040
185 | }
186 | for (a = 0; a <= h; a += 1) {
187 | v[a] = b[a] ^ 909522486, w[a] = b[a]
188 | ^ 1549556828;
189 | }
190 | l = q(v, l);
191 | e = m;
192 | I = !0
193 | };
194 | this.update = function (a) {
195 | var c, b, k, f = 0, g = m >>> 5;
196 | c = d(a, h, n);
197 | a = c.binLen;
198 | b = c.value;
199 | c = a >>> 5;
200 | for (k = 0; k < c; k += g) {
201 | f + m <= a && (l = q(b.slice(k, k + g),
202 | l), f += m);
203 | }
204 | e += f;
205 | h = b.slice(f >>> 5);
206 | n = a % m;
207 | y = !0
208 | };
209 | this.getHash = function (a, b) {
210 | var k, g, d, m;
211 | if (!0 === I) {
212 | throw Error("Cannot call getHash after setting HMAC key");
213 | }
214 | d = N(b);
215 | if (!0 === z) {
216 | if (-1 === d.shakeLen) {
217 | throw Error(
218 | "shakeLen must be specified in options");
219 | }
220 | f = d.shakeLen
221 | }
222 | switch (a) {
223 | case "HEX":
224 | k = function (a) {
225 | return O(a, f, x, d)
226 | };
227 | break;
228 | case "B64":
229 | k = function (a) {
230 | return P(a, f, x, d)
231 | };
232 | break;
233 | case "BYTES":
234 | k = function (a) {
235 | return Q(a, f, x)
236 | };
237 | break;
238 | case "ARRAYBUFFER":
239 | try {
240 | g = new ArrayBuffer(0)
241 | } catch (p) {
242 | throw Error("ARRAYBUFFER not supported by this environment");
243 | }
244 | k = function (a) {
245 | return R(a, f, x)
246 | };
247 | break;
248 | default:
249 | throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER");
250 | }
251 | m = u(h.slice(), n, e, r(l), f);
252 | for (g = 1; g < t; g += 1) {
253 | !0 === z && 0 !== f % 32 && (m[m.length
254 | - 1] &= 16777215 >>> 24 - f % 32), m = u(m, f,
255 | 0, A(c), f);
256 | }
257 | return k(m)
258 | };
259 | this.getHMAC = function (a, b) {
260 | var k, g, d, p;
261 | if (!1 === I) {
262 | throw Error(
263 | "Cannot call getHMAC without first setting HMAC key");
264 | }
265 | d = N(b);
266 | switch (a) {
267 | case "HEX":
268 | k = function (a) {
269 | return O(a, f, x, d)
270 | };
271 | break;
272 | case "B64":
273 | k = function (a) {
274 | return P(a, f, x, d)
275 | };
276 | break;
277 | case "BYTES":
278 | k = function (a) {
279 | return Q(a, f, x)
280 | };
281 | break;
282 | case "ARRAYBUFFER":
283 | try {
284 | k = new ArrayBuffer(0)
285 | } catch (v) {
286 | throw Error("ARRAYBUFFER not supported by this environment");
287 | }
288 | k = function (a) {
289 | return R(a, f, x)
290 | };
291 | break;
292 | default:
293 | throw Error("outputFormat must be HEX, B64, BYTES, or ARRAYBUFFER");
294 | }
295 | g = u(h.slice(), n, e, r(l), f);
296 | p = q(w, A(c));
297 | p = u(g, f, m, p, f);
298 | return k(p)
299 | }
300 | }
301 |
302 | function b(c, a) {
303 | this.a = c;
304 | this.b = a
305 | }
306 |
307 | function O(c, a, b, e) {
308 | var h = "";
309 | a /= 8;
310 | var n, g, d;
311 | d = -1 === b ? 3 : 0;
312 | for (n = 0; n < a; n += 1) {
313 | g = c[n >>> 2] >>> 8 * (d + n % 4
314 | * b), h += "0123456789abcdef".charAt(g >>> 4 & 15)
315 | + "0123456789abcdef".charAt(g & 15);
316 | }
317 | return e.outputUpper ? h.toUpperCase() : h
318 | }
319 |
320 | function P(c, a, b, e) {
321 | var h = "", n = a / 8, g, d, p, f;
322 | f = -1 === b ? 3 : 0;
323 | for (g = 0; g < n; g += 3) {
324 | for (d = g + 1 < n ? c[g + 1 >>> 2] : 0, p = g
325 | + 2 < n ? c[g + 2 >>> 2] : 0, p = (c[g >>> 2] >>> 8 * (f + g % 4 * b)
326 | & 255)
327 | << 16 | (d >>> 8 * (f + (g + 1) % 4 * b) & 255) << 8 | p >>> 8 * (f +
328 | (g + 2) % 4 * b) & 255, d = 0; 4 > d; d += 1) {
329 | 8 * g + 6 * d <= a
330 | ? h += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(p
331 | >>> 6 * (3 - d) & 63) : h += e.b64Pad;
332 | }
333 | }
334 | return h
335 | }
336 |
337 | function Q(c, a, b) {
338 | var e = "";
339 | a /= 8;
340 | var h, d, g;
341 | g = -1 === b ? 3 : 0;
342 | for (h = 0; h < a; h += 1) {
343 | d = c[h >>> 2] >>> 8 * (g + h % 4 * b)
344 | & 255, e += String.fromCharCode(d);
345 | }
346 | return e
347 | }
348 |
349 | function R(c, a, b) {
350 | a /= 8;
351 | var e, h = new ArrayBuffer(a), d, g;
352 | g = new Uint8Array(h);
353 | d = -1 === b ? 3 : 0;
354 | for (e = 0; e < a; e += 1) {
355 | g[e] = c[e >>> 2] >>> 8 * (d + e % 4 * b) & 255;
356 | }
357 | return h
358 | }
359 |
360 | function N(c) {
361 | var a = {outputUpper: !1, b64Pad: "=", shakeLen: -1};
362 | c = c || {};
363 | a.outputUpper = c.outputUpper || !1;
364 | !0 === c.hasOwnProperty("b64Pad") && (a.b64Pad = c.b64Pad);
365 | if (!0 === c.hasOwnProperty("shakeLen")) {
366 | if (0 !== c.shakeLen % 8) {
367 | throw Error("shakeLen must be a multiple of 8");
368 | }
369 | a.shakeLen = c.shakeLen
370 | }
371 | if ("boolean" !== typeof a.outputUpper) {
372 | throw Error(
373 | "Invalid outputUpper formatting option");
374 | }
375 | if ("string" !== typeof a.b64Pad) {
376 | throw Error(
377 | "Invalid b64Pad formatting option");
378 | }
379 | return a
380 | }
381 |
382 | function M(c, a, b) {
383 | switch (a) {
384 | case "UTF8":
385 | case "UTF16BE":
386 | case "UTF16LE":
387 | break;
388 | default:
389 | throw Error("encoding must be UTF8, UTF16BE, or UTF16LE");
390 | }
391 | switch (c) {
392 | case "HEX":
393 | c = function (a, c, d) {
394 | var g = a.length, l, p, f, m, q, u;
395 | if (0 !== g % 2) {
396 | throw Error(
397 | "String of HEX type must be in byte increments");
398 | }
399 | c = c || [0];
400 | d = d || 0;
401 | q = d >>> 3;
402 | u = -1 === b ? 3 : 0;
403 | for (l = 0; l < g; l += 2) {
404 | p = parseInt(a.substr(l, 2), 16);
405 | if (isNaN(p)) {
406 | throw Error(
407 | "String of HEX type contains invalid characters");
408 | }
409 | m = (l >>> 1) + q;
410 | for (f = m >>> 2; c.length <= f;) {
411 | c.push(0);
412 | }
413 | c[f] |= p << 8 * (u + m % 4 * b)
414 | }
415 | return {value: c, binLen: 4 * g + d}
416 | };
417 | break;
418 | case "TEXT":
419 | c = function (c, h, d) {
420 | var g, l, p = 0, f, m, q, u, r, t;
421 | h = h || [0];
422 | d = d || 0;
423 | q = d >>> 3;
424 | if ("UTF8" === a) {
425 | for (t = -1 ===
426 | b ? 3 : 0, f = 0; f < c.length; f += 1) {
427 | for (g = c.charCodeAt(
428 | f), l = [], 128 > g ? l.push(g) : 2048 > g ? (l.push(192 | g
429 | >>> 6), l.push(128 | g & 63)) : 55296 > g || 57344 <= g
430 | ? l.push(224 | g >>> 12, 128 | g >>> 6 & 63, 128 | g & 63)
431 | : (f += 1, g = 65536 + ((g & 1023) << 10 | c.charCodeAt(f)
432 | & 1023), l.push(240 | g >>> 18, 128 | g >>> 12 & 63, 128
433 | | g
434 | >>> 6 & 63, 128 | g & 63)), m = 0; m < l.length; m += 1) {
435 | r = p + q;
436 | for (u = r >>> 2; h.length <= u;) {
437 | h.push(0);
438 | }
439 | h[u] |= l[m] << 8 * (t + r % 4 * b);
440 | p += 1
441 | }
442 | }
443 | } else if ("UTF16BE" === a || "UTF16LE" === a) {
444 | for (t = -1 === b ? 2
445 | : 0, l = "UTF16LE" === a && 1 !== b || "UTF16LE" !== a && 1
446 | === b, f = 0; f < c.length; f += 1) {
447 | g = c.charCodeAt(f);
448 | !0 === l && (m = g & 255, g = m << 8 | g >>> 8);
449 | r = p + q;
450 | for (u = r >>> 2; h.length <= u;) {
451 | h.push(0);
452 | }
453 | h[u] |= g << 8 * (t + r % 4 * b);
454 | p += 2
455 | }
456 | }
457 | return {value: h, binLen: 8 * p + d}
458 | };
459 | break;
460 | case "B64":
461 | c = function (a, c, d) {
462 | var g = 0, l, p, f, m, q, u, r, t;
463 | if (-1 === a.search(/^[a-zA-Z0-9=+\/]+$/)) {
464 | throw Error(
465 | "Invalid character in base-64 string");
466 | }
467 | p = a.indexOf("=");
468 | a = a.replace(/\=/g, "");
469 | if (-1 !== p && p < a.length) {
470 | throw Error(
471 | "Invalid '=' found in base-64 string");
472 | }
473 | c = c || [0];
474 | d = d || 0;
475 | u = d >>> 3;
476 | t = -1 === b ? 3 : 0;
477 | for (p = 0; p < a.length; p += 4) {
478 | q = a.substr(p, 4);
479 | for (f = m = 0; f < q.length;
480 | f += 1) {
481 | l = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(
482 | q[f]),
483 | m |= l << 18 - 6 * f;
484 | }
485 | for (f = 0; f < q.length - 1; f += 1) {
486 | r = g + u;
487 | for (l = r >>> 2; c.length <= l;) {
488 | c.push(0);
489 | }
490 | c[l] |= (m >>> 16 - 8 * f & 255) << 8 * (t + r % 4 * b);
491 | g += 1
492 | }
493 | }
494 | return {value: c, binLen: 8 * g + d}
495 | };
496 | break;
497 | case "BYTES":
498 | c = function (a, c, d) {
499 | var g, l, p, f, m, q;
500 | c = c || [0];
501 | d = d || 0;
502 | p = d >>> 3;
503 | q = -1 === b ? 3 : 0;
504 | for (l = 0; l < a.length; l += 1) {
505 | g = a.charCodeAt(l), m = l
506 | + p, f = m >>> 2, c.length <= f && c.push(0), c[f] |= g << 8
507 | * (q
508 | + m % 4 * b);
509 | }
510 | return {value: c, binLen: 8 * a.length + d}
511 | };
512 | break;
513 | case "ARRAYBUFFER":
514 | try {
515 | c = new ArrayBuffer(0)
516 | } catch (e) {
517 | throw Error("ARRAYBUFFER not supported by this environment");
518 | }
519 | c =
520 | function (a, c, d) {
521 | var g, l, p, f, m, q;
522 | c = c || [0];
523 | d = d || 0;
524 | l = d >>> 3;
525 | m = -1 === b ? 3 : 0;
526 | q = new Uint8Array(a);
527 | for (g = 0; g < a.byteLength; g += 1) {
528 | f = g + l, p = f
529 | >>> 2, c.length <= p && c.push(0), c[p] |= q[g] << 8 * (m
530 | + f
531 | % 4 * b);
532 | }
533 | return {value: c, binLen: 8 * a.byteLength + d}
534 | };
535 | break;
536 | default:
537 | throw Error("format must be HEX, TEXT, B64, BYTES, or ARRAYBUFFER");
538 | }
539 | return c
540 | }
541 |
542 | function y(c, a) {
543 | return c << a | c >>> 32 - a
544 | }
545 |
546 | function S(c, a) {
547 | return 32 < a ? (a -= 32, new b(c.b << a | c.a >>> 32 - a, c.a << a | c.b
548 | >>> 32 - a)) : 0 !== a ? new b(c.a << a | c.b >>> 32 - a, c.b << a | c.a
549 | >>> 32 - a) : c
550 | }
551 |
552 | function w(c, a) {
553 | return c >>>
554 | a | c << 32 - a
555 | }
556 |
557 | function t(c, a) {
558 | var k = null, k = new b(c.a, c.b);
559 | return k = 32 >= a ? new b(k.a >>> a | k.b << 32 - a & 4294967295, k.b >>> a
560 | | k.a << 32 - a & 4294967295) : new b(k.b >>> a - 32 | k.a << 64 - a
561 | & 4294967295, k.a >>> a - 32 | k.b << 64 - a & 4294967295)
562 | }
563 |
564 | function T(c, a) {
565 | var k = null;
566 | return k = 32 >= a ? new b(c.a >>> a, c.b >>> a | c.a << 32 - a
567 | & 4294967295) : new b(0, c.a >>> a - 32)
568 | }
569 |
570 | function aa(c, a, b) {
571 | return c & a ^ ~c & b
572 | }
573 |
574 | function ba(c, a, k) {
575 | return new b(c.a & a.a ^ ~c.a & k.a, c.b & a.b ^ ~c.b & k.b)
576 | }
577 |
578 | function U(c, a, b) {
579 | return c & a ^ c & b ^ a & b
580 | }
581 |
582 | function ca(c, a, k) {
583 | return new b(c.a & a.a ^ c.a & k.a ^ a.a &
584 | k.a, c.b & a.b ^ c.b & k.b ^ a.b & k.b)
585 | }
586 |
587 | function da(c) {
588 | return w(c, 2) ^ w(c, 13) ^ w(c, 22)
589 | }
590 |
591 | function ea(c) {
592 | var a = t(c, 28), k = t(c, 34);
593 | c = t(c, 39);
594 | return new b(a.a ^ k.a ^ c.a, a.b ^ k.b ^ c.b)
595 | }
596 |
597 | function fa(c) {
598 | return w(c, 6) ^ w(c, 11) ^ w(c, 25)
599 | }
600 |
601 | function ga(c) {
602 | var a = t(c, 14), k = t(c, 18);
603 | c = t(c, 41);
604 | return new b(a.a ^ k.a ^ c.a, a.b ^ k.b ^ c.b)
605 | }
606 |
607 | function ha(c) {
608 | return w(c, 7) ^ w(c, 18) ^ c >>> 3
609 | }
610 |
611 | function ia(c) {
612 | var a = t(c, 1), k = t(c, 8);
613 | c = T(c, 7);
614 | return new b(a.a ^ k.a ^ c.a, a.b ^ k.b ^ c.b)
615 | }
616 |
617 | function ja(c) {
618 | return w(c, 17) ^ w(c, 19) ^ c >>> 10
619 | }
620 |
621 | function ka(c) {
622 | var a = t(c, 19), k = t(c, 61);
623 | c = T(c, 6);
624 | return new b(a.a ^ k.a ^ c.a, a.b ^ k.b ^ c.b)
625 | }
626 |
627 | function G(c, a) {
628 | var b = (c & 65535) + (a & 65535);
629 | return ((c >>> 16) + (a >>> 16) + (b >>> 16) & 65535) << 16 | b & 65535
630 | }
631 |
632 | function la(c, a, b, e) {
633 | var h = (c & 65535) + (a & 65535) + (b & 65535) + (e & 65535);
634 | return ((c >>> 16) + (a >>> 16) + (b >>> 16) + (e >>> 16) + (h >>> 16)
635 | & 65535) << 16 | h & 65535
636 | }
637 |
638 | function H(c, a, b, e, h) {
639 | var d = (c & 65535) + (a & 65535) + (b & 65535) + (e & 65535) + (h & 65535);
640 | return ((c >>> 16) + (a >>> 16) + (b >>> 16) + (e >>> 16) + (h >>> 16) + (d
641 | >>> 16) & 65535) << 16 | d & 65535
642 | }
643 |
644 | function ma(c, a) {
645 | var d, e, h;
646 | d = (c.b & 65535) + (a.b & 65535);
647 | e = (c.b >>> 16) +
648 | (a.b >>> 16) + (d >>> 16);
649 | h = (e & 65535) << 16 | d & 65535;
650 | d = (c.a & 65535) + (a.a & 65535) + (e >>> 16);
651 | e = (c.a >>> 16) + (a.a >>> 16) + (d >>> 16);
652 | return new b((e & 65535) << 16 | d & 65535, h)
653 | }
654 |
655 | function na(c, a, d, e) {
656 | var h, n, g;
657 | h = (c.b & 65535) + (a.b & 65535) + (d.b & 65535) + (e.b & 65535);
658 | n = (c.b >>> 16) + (a.b >>> 16) + (d.b >>> 16) + (e.b >>> 16) + (h >>> 16);
659 | g = (n & 65535) << 16 | h & 65535;
660 | h = (c.a & 65535) + (a.a & 65535) + (d.a & 65535) + (e.a & 65535) + (n
661 | >>> 16);
662 | n = (c.a >>> 16) + (a.a >>> 16) + (d.a >>> 16) + (e.a >>> 16) + (h >>> 16);
663 | return new b((n & 65535) << 16 | h & 65535, g)
664 | }
665 |
666 | function oa(c, a, d, e, h) {
667 | var n, g, l;
668 | n = (c.b &
669 | 65535) + (a.b & 65535) + (d.b & 65535) + (e.b & 65535) + (h.b & 65535);
670 | g = (c.b >>> 16) + (a.b >>> 16) + (d.b >>> 16) + (e.b >>> 16) + (h.b >>> 16)
671 | + (n >>> 16);
672 | l = (g & 65535) << 16 | n & 65535;
673 | n = (c.a & 65535) + (a.a & 65535) + (d.a & 65535) + (e.a & 65535) + (h.a
674 | & 65535) + (g >>> 16);
675 | g = (c.a >>> 16) + (a.a >>> 16) + (d.a >>> 16) + (e.a >>> 16) + (h.a >>> 16)
676 | + (n >>> 16);
677 | return new b((g & 65535) << 16 | n & 65535, l)
678 | }
679 |
680 | function B(c, a) {
681 | return new b(c.a ^ a.a, c.b ^ a.b)
682 | }
683 |
684 | function A(c) {
685 | var a = [], d;
686 | if ("SHA-1" === c) {
687 | a = [1732584193, 4023233417, 2562383102, 271733878,
688 | 3285377520];
689 | } else if (0 === c.lastIndexOf("SHA-", 0)) {
690 | switch (a =
691 | [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025,
692 | 1694076839, 3204075428], d = [1779033703, 3144134277, 1013904242,
693 | 2773480762, 1359893119, 2600822924, 528734635, 1541459225], c) {
694 | case "SHA-224":
695 | break;
696 | case "SHA-256":
697 | a = d;
698 | break;
699 | case "SHA-384":
700 | a = [new b(3418070365, a[0]), new b(1654270250, a[1]),
701 | new b(2438529370, a[2]), new b(355462360, a[3]),
702 | new b(1731405415, a[4]), new b(41048885895, a[5]),
703 | new b(3675008525, a[6]), new b(1203062813, a[7])];
704 | break;
705 | case "SHA-512":
706 | a = [new b(d[0], 4089235720), new b(d[1], 2227873595),
707 | new b(d[2], 4271175723), new b(d[3], 1595750129),
708 | new b(d[4], 2917565137), new b(d[5], 725511199),
709 | new b(d[6], 4215389547), new b(d[7], 327033209)];
710 | break;
711 | default:
712 | throw Error("Unknown SHA variant");
713 | }
714 | } else if (0 === c.lastIndexOf("SHA3-", 0) || 0 === c.lastIndexOf("SHAKE",
715 | 0)) {
716 | for (c = 0; 5 > c; c += 1) {
717 | a[c] = [new b(0, 0), new b(0, 0),
718 | new b(0, 0), new b(0, 0), new b(0, 0)];
719 | }
720 | } else {
721 | throw Error(
722 | "No SHA variants supported");
723 | }
724 | return a
725 | }
726 |
727 | function K(c, a) {
728 | var b = [], e, d, n, g, l, p, f;
729 | e = a[0];
730 | d = a[1];
731 | n = a[2];
732 | g = a[3];
733 | l = a[4];
734 | for (f = 0; 80 > f; f += 1) {
735 | b[f] = 16 > f ? c[f] : y(b[f -
736 | 3] ^ b[f - 8] ^ b[f - 14] ^ b[f - 16], 1), p = 20 > f ? H(y(e, 5), d & n
737 | ^ ~d & g, l, 1518500249, b[f]) : 40 > f ? H(y(e, 5), d ^ n ^ g, l,
738 | 1859775393, b[f]) : 60 > f ? H(y(e, 5), U(d, n, g), l, 2400959708,
739 | b[f])
740 | : H(y(e, 5), d ^ n ^ g, l, 3395469782, b[f]), l = g, g = n, n = y(d,
741 | 30), d = e, e = p;
742 | }
743 | a[0] = G(e, a[0]);
744 | a[1] = G(d, a[1]);
745 | a[2] = G(n, a[2]);
746 | a[3] = G(g, a[3]);
747 | a[4] = G(l, a[4]);
748 | return a
749 | }
750 |
751 | function Z(c, a, b, e) {
752 | var d;
753 | for (d = (a + 65 >>> 9 << 4) + 15; c.length <= d;) {
754 | c.push(0);
755 | }
756 | c[a >>> 5] |= 128 << 24 - a % 32;
757 | a += b;
758 | c[d] = a & 4294967295;
759 | c[d - 1] = a / 4294967296 | 0;
760 | a = c.length;
761 | for (d = 0; d < a; d += 16) {
762 | e = K(c.slice(d, d + 16), e);
763 | }
764 | return e
765 | }
766 |
767 | function L(c,
768 | a, k) {
769 | var e, h, n, g, l, p, f, m, q, u, r, t, v, w, y, A, z, x, F, B, C, D,
770 | E = [], J;
771 | if ("SHA-224" === k || "SHA-256"
772 | === k) {
773 | u = 64, t = 1, D = Number, v = G, w = la, y = H, A = ha, z = ja, x = da, F = fa, C = U, B = aa, J = d;
774 | } else if ("SHA-384"
775 | === k || "SHA-512"
776 | === k) {
777 | u = 80, t = 2, D = b, v = ma, w = na, y = oa, A = ia, z = ka, x = ea, F = ga, C = ca, B = ba, J = V;
778 | } else {
779 | throw Error(
780 | "Unexpected error in SHA-2 implementation");
781 | }
782 | k = a[0];
783 | e = a[1];
784 | h = a[2];
785 | n = a[3];
786 | g = a[4];
787 | l = a[5];
788 | p = a[6];
789 | f = a[7];
790 | for (r = 0; r < u; r += 1) {
791 | 16 > r ? (q = r * t, m = c.length <= q ? 0
792 | : c[q], q = c.length <= q + 1 ? 0 : c[q + 1], E[r] = new D(m, q))
793 | : E[r] = w(z(E[r - 2]), E[r - 7], A(E[r - 15]), E[r -
794 | 16]), m = y(f, F(g), B(g, l, p), J[r], E[r]), q = v(x(k),
795 | C(k, e, h)), f = p, p = l, l = g, g = v(n,
796 | m), n = h, h = e, e = k, k = v(m, q);
797 | }
798 | a[0] = v(k, a[0]);
799 | a[1] = v(e, a[1]);
800 | a[2] = v(h, a[2]);
801 | a[3] = v(n, a[3]);
802 | a[4] = v(g, a[4]);
803 | a[5] = v(l, a[5]);
804 | a[6] = v(p, a[6]);
805 | a[7] = v(f, a[7]);
806 | return a
807 | }
808 |
809 | function D(c, a) {
810 | var d, e, h, n, g = [], l = [];
811 | if (null !== c) {
812 | for (e = 0; e < c.length; e += 2) {
813 | a[(e >>> 1) % 5][(e >>> 1)
814 | / 5 | 0] = B(a[(e >>> 1) % 5][(e >>> 1) / 5 | 0],
815 | new b(c[e + 1], c[e]));
816 | }
817 | }
818 | for (d = 0; 24 > d; d += 1) {
819 | n = A("SHA3-");
820 | for (e = 0; 5 > e; e += 1) {
821 | h = a[e][0];
822 | var p = a[e][1], f = a[e][2], m = a[e][3], q = a[e][4];
823 | g[e] = new b(h.a ^ p.a ^ f.a ^
824 | m.a ^ q.a, h.b ^ p.b ^ f.b ^ m.b ^ q.b)
825 | }
826 | for (e = 0; 5 > e; e += 1) {
827 | l[e] = B(g[(e + 4) % 5], S(g[(e + 1) % 5], 1));
828 | }
829 | for (e = 0; 5 > e; e += 1) {
830 | for (h = 0; 5 > h; h += 1) {
831 | a[e][h] = B(a[e][h],
832 | l[e]);
833 | }
834 | }
835 | for (e = 0; 5 > e; e += 1) {
836 | for (h = 0; 5 > h; h += 1) {
837 | n[h][(2 * e + 3 * h)
838 | % 5] = S(a[e][h], W[e][h]);
839 | }
840 | }
841 | for (e = 0; 5 > e; e += 1) {
842 | for (h = 0; 5 > h; h += 1) {
843 | a[e][h] = B(n[e][h],
844 | new b(~n[(e + 1) % 5][h].a & n[(e + 2) % 5][h].a, ~n[(e + 1)
845 | % 5][h].b
846 | & n[(e + 2) % 5][h].b));
847 | }
848 | }
849 | a[0][0] = B(a[0][0], X[d])
850 | }
851 | return a
852 | }
853 |
854 | var d, V, W, X;
855 | d = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993,
856 | 2453635748, 2870763221, 3624381080, 310598401, 607225278,
857 | 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401,
858 | 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692,
859 | 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891,
860 | 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372,
861 | 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921,
862 | 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909,
863 | 275423344, 430227734, 506948616, 659060556, 883997877, 958139571,
864 | 1322822218, 1537002063, 1747873779, 1955562222, 2024104815,
865 | 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
866 | V = [new b(d[0], 3609767458), new b(d[1], 602891725), new b(d[2], 3964484399),
867 | new b(d[3], 2173295548), new b(d[4], 4081628472), new b(d[5], 3053834265),
868 | new b(d[6], 2937671579), new b(d[7], 3664609560), new b(d[8], 2734883394),
869 | new b(d[9], 1164996542), new b(d[10], 1323610764), new b(d[11], 3590304994),
870 | new b(d[12], 4068182383), new b(d[13], 991336113), new b(d[14], 633803317),
871 | new b(d[15], 3479774868), new b(d[16], 2666613458), new b(d[17], 944711139),
872 | new b(d[18], 2341262773),
873 | new b(d[19], 2007800933), new b(d[20], 1495990901),
874 | new b(d[21], 1856431235), new b(d[22], 3175218132),
875 | new b(d[23], 2198950837), new b(d[24], 3999719339), new b(d[25], 766784016),
876 | new b(d[26], 2566594879), new b(d[27], 3203337956),
877 | new b(d[28], 1034457026), new b(d[29], 2466948901),
878 | new b(d[30], 3758326383), new b(d[31], 168717936), new b(d[32], 1188179964),
879 | new b(d[33], 1546045734), new b(d[34], 1522805485),
880 | new b(d[35], 2643833823), new b(d[36], 2343527390),
881 | new b(d[37], 1014477480), new b(d[38], 1206759142), new b(d[39], 344077627),
882 | new b(d[40], 1290863460), new b(d[41], 3158454273),
883 | new b(d[42], 3505952657), new b(d[43], 106217008), new b(d[44], 3606008344),
884 | new b(d[45], 1432725776), new b(d[46], 1467031594), new b(d[47], 851169720),
885 | new b(d[48], 3100823752), new b(d[49], 1363258195),
886 | new b(d[50], 3750685593), new b(d[51], 3785050280),
887 | new b(d[52], 3318307427), new b(d[53], 3812723403),
888 | new b(d[54], 2003034995), new b(d[55], 3602036899),
889 | new b(d[56], 1575990012), new b(d[57], 1125592928),
890 | new b(d[58], 2716904306), new b(d[59], 442776044), new b(d[60], 593698344),
891 | new b(d[61],
892 | 3733110249), new b(d[62], 2999351573), new b(d[63], 3815920427),
893 | new b(3391569614, 3928383900), new b(3515267271, 566280711),
894 | new b(3940187606, 3454069534), new b(4118630271, 4000239992),
895 | new b(116418474, 1914138554), new b(174292421, 2731055270),
896 | new b(289380356, 3203993006), new b(460393269, 320620315),
897 | new b(685471733, 587496836), new b(852142971, 1086792851),
898 | new b(1017036298, 365543100), new b(1126000580, 2618297676),
899 | new b(1288033470, 3409855158), new b(1501505948, 4234509866),
900 | new b(1607167915, 987167468), new b(1816402316,
901 | 1246189591)];
902 | X = [new b(0, 1), new b(0, 32898), new b(2147483648, 32906),
903 | new b(2147483648, 2147516416), new b(0, 32907), new b(0, 2147483649),
904 | new b(2147483648, 2147516545), new b(2147483648, 32777), new b(0, 138),
905 | new b(0, 136), new b(0, 2147516425), new b(0, 2147483658),
906 | new b(0, 2147516555), new b(2147483648, 139), new b(2147483648, 32905),
907 | new b(2147483648, 32771), new b(2147483648, 32770), new b(2147483648, 128),
908 | new b(0, 32778), new b(2147483648, 2147483658),
909 | new b(2147483648, 2147516545), new b(2147483648, 32896),
910 | new b(0, 2147483649),
911 | new b(2147483648, 2147516424)];
912 | W = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61],
913 | [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]];
914 | "function" === typeof define && define.amd ? define(function () {
915 | return C
916 | }) : "undefined" !== typeof exports ? ("undefined" !== typeof module
917 | && module.exports && (module.exports = C), exports = C) : Y.jsSHA = C
918 | })(this);
919 |
--------------------------------------------------------------------------------
/src/lib/sha256.js:
--------------------------------------------------------------------------------
1 | /*
2 | A JavaScript implementation of the SHA family of hashes, as
3 | defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding
4 | HMAC implementation as defined in FIPS PUB 198a
5 |
6 | Copyright Brian Turek 2008-2017
7 | Distributed under the BSD License
8 | See http://caligatio.github.com/jsSHA/ for more information
9 |
10 | Several functions taken from Paul Johnston
11 | */
12 | 'use strict';
13 | (function (I) {
14 | function w(c, a, d) {
15 | var l = 0, b = [], g = 0, f, n, k, e, h, q, y, p, m = !1, t = [], r = [], u,
16 | z = !1;
17 | d = d || {};
18 | f = d.encoding || "UTF8";
19 | u = d.numRounds || 1;
20 | if (u !== parseInt(u, 10) || 1 > u) {
21 | throw Error(
22 | "numRounds must a integer >= 1");
23 | }
24 | if (0 === c.lastIndexOf("SHA-", 0)) {
25 | if (q = function (b, a) {
26 | return A(b, a, c)
27 | }, y = function (b, a, l, f) {
28 | var g, e;
29 | if ("SHA-224" === c || "SHA-256" === c) {
30 | g = (a + 65 >>> 9 << 4)
31 | + 15, e = 16;
32 | } else {
33 | throw Error(
34 | "Unexpected error in SHA-2 implementation");
35 | }
36 | for (; b.length <= g;) {
37 | b.push(0);
38 | }
39 | b[a >>> 5] |= 128 << 24 - a % 32;
40 | a = a + l;
41 | b[g] = a & 4294967295;
42 | b[g - 1] = a / 4294967296 | 0;
43 | l = b.length;
44 | for (a = 0; a < l; a += e) {
45 | f = A(b.slice(a, a + e), f, c);
46 | }
47 | if ("SHA-224" === c) {
48 | b = [f[0], f[1], f[2], f[3], f[4], f[5],
49 | f[6]];
50 | } else if ("SHA-256" === c) {
51 | b = f;
52 | } else {
53 | throw Error(
54 | "Unexpected error in SHA-2 implementation");
55 | }
56 | return b
57 | }, p = function (b) {
58 | return b.slice()
59 | }, "SHA-224" === c) {
60 | h = 512, e = 224;
61 | } else if ("SHA-256"
62 | === c) {
63 | h = 512, e = 256;
64 | } else {
65 | throw Error(
66 | "Chosen SHA variant is not supported");
67 | }
68 | } else {
69 | throw Error(
70 | "Chosen SHA variant is not supported");
71 | }
72 | k = B(a, f);
73 | n = x(c);
74 | this.setHMACKey = function (b, a, g) {
75 | var e;
76 | if (!0 === m) {
77 | throw Error("HMAC key already set");
78 | }
79 | if (!0 === z) {
80 | throw Error("Cannot set HMAC key after calling update");
81 | }
82 | f = (g || {}).encoding || "UTF8";
83 | a = B(a, f)(b);
84 | b = a.binLen;
85 | a = a.value;
86 | e = h >>> 3;
87 | g = e / 4 - 1;
88 | if (e < b / 8) {
89 | for (a = y(a, b, 0, x(c)); a.length <= g;) {
90 | a.push(0);
91 | }
92 | a[g] &= 4294967040
93 | } else if (e > b / 8) {
94 | for (; a.length <= g;) {
95 | a.push(0);
96 | }
97 | a[g] &= 4294967040
98 | }
99 | for (b = 0; b <= g; b += 1) {
100 | t[b] = a[b] ^ 909522486, r[b] = a[b]
101 | ^ 1549556828;
102 | }
103 | n = q(t, n);
104 | l = h;
105 | m = !0
106 | };
107 | this.update = function (a) {
108 | var c, f, e, d = 0, p = h >>> 5;
109 | c = k(a, b, g);
110 | a = c.binLen;
111 | f = c.value;
112 | c = a >>> 5;
113 | for (e = 0; e < c; e += p) {
114 | d + h <= a && (n = q(f.slice(e, e + p),
115 | n), d += h);
116 | }
117 | l += d;
118 | b = f.slice(d >>>
119 | 5);
120 | g = a % h;
121 | z = !0
122 | };
123 | this.getHash = function (a, f) {
124 | var d, h, k, q;
125 | if (!0 === m) {
126 | throw Error("Cannot call getHash after setting HMAC key");
127 | }
128 | k = C(f);
129 | switch (a) {
130 | case "HEX":
131 | d = function (a) {
132 | return D(a, e, k)
133 | };
134 | break;
135 | case "B64":
136 | d = function (a) {
137 | return E(a, e, k)
138 | };
139 | break;
140 | case "BYTES":
141 | d = function (a) {
142 | return F(a, e)
143 | };
144 | break;
145 | case "ARRAYBUFFER":
146 | try {
147 | h = new ArrayBuffer(0)
148 | } catch (v) {
149 | throw Error("ARRAYBUFFER not supported by this environment");
150 | }
151 | d = function (a) {
152 | return G(a, e)
153 | };
154 | break;
155 | default:
156 | throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER");
157 | }
158 | q = y(b.slice(), g, l, p(n));
159 | for (h = 1; h < u; h += 1) {
160 | q = y(q, e, 0, x(c));
161 | }
162 | return d(q)
163 | };
164 | this.getHMAC = function (a, f) {
165 | var d, k, t, u;
166 | if (!1 === m) {
167 | throw Error(
168 | "Cannot call getHMAC without first setting HMAC key");
169 | }
170 | t = C(f);
171 | switch (a) {
172 | case "HEX":
173 | d = function (a) {
174 | return D(a, e, t)
175 | };
176 | break;
177 | case "B64":
178 | d = function (a) {
179 | return E(a, e, t)
180 | };
181 | break;
182 | case "BYTES":
183 | d = function (a) {
184 | return F(a, e)
185 | };
186 | break;
187 | case "ARRAYBUFFER":
188 | try {
189 | d = new ArrayBuffer(0)
190 | } catch (v) {
191 | throw Error("ARRAYBUFFER not supported by this environment");
192 | }
193 | d = function (a) {
194 | return G(a, e)
195 | };
196 | break;
197 | default:
198 | throw Error("outputFormat must be HEX, B64, BYTES, or ARRAYBUFFER");
199 | }
200 | k = y(b.slice(), g, l, p(n));
201 | u = q(r, x(c));
202 | u = y(k, e, h, u);
203 | return d(u)
204 | }
205 | }
206 |
207 | function m() {
208 | }
209 |
210 | function D(c, a, d) {
211 | var l = "";
212 | a /= 8;
213 | var b, g;
214 | for (b = 0; b < a; b += 1) {
215 | g = c[b >>> 2] >>> 8 * (3 + b % 4
216 | * -1), l += "0123456789abcdef".charAt(g >>> 4 & 15)
217 | + "0123456789abcdef".charAt(g & 15);
218 | }
219 | return d.outputUpper ? l.toUpperCase() : l
220 | }
221 |
222 | function E(c, a, d) {
223 | var l = "", b = a / 8, g, f, n;
224 | for (g = 0; g < b; g += 3) {
225 | for (f = g + 1 < b ? c[g + 1 >>> 2] : 0, n = g
226 | + 2 < b ? c[g + 2 >>> 2] : 0, n = (c[g >>> 2] >>> 8 * (3 + g % 4 * -1)
227 | & 255) << 16 | (f >>> 8 * (3 + (g + 1) % 4 * -1) & 255) << 8 | n >>> 8
228 | * (3 + (g + 2) % 4 * -1) & 255, f = 0; 4 > f; f += 1) {
229 | 8 * g + 6 * f <= a
230 | ? l += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(n
231 | >>>
232 | 6 * (3 - f) & 63) : l += d.b64Pad;
233 | }
234 | }
235 | return l
236 | }
237 |
238 | function F(c, a) {
239 | var d = "", l = a / 8, b, g;
240 | for (b = 0; b < l; b += 1) {
241 | g = c[b >>> 2] >>> 8 * (3 + b % 4 * -1)
242 | & 255, d += String.fromCharCode(g);
243 | }
244 | return d
245 | }
246 |
247 | function G(c, a) {
248 | var d = a / 8, l, b = new ArrayBuffer(d), g;
249 | g = new Uint8Array(b);
250 | for (l = 0; l < d; l += 1) {
251 | g[l] = c[l >>> 2] >>> 8 * (3 + l % 4 * -1) & 255;
252 | }
253 | return b
254 | }
255 |
256 | function C(c) {
257 | var a = {outputUpper: !1, b64Pad: "=", shakeLen: -1};
258 | c = c || {};
259 | a.outputUpper = c.outputUpper || !1;
260 | !0 === c.hasOwnProperty("b64Pad") && (a.b64Pad = c.b64Pad);
261 | if ("boolean" !== typeof a.outputUpper) {
262 | throw Error(
263 | "Invalid outputUpper formatting option");
264 | }
265 | if ("string" !== typeof a.b64Pad) {
266 | throw Error(
267 | "Invalid b64Pad formatting option");
268 | }
269 | return a
270 | }
271 |
272 | function B(c, a) {
273 | var d;
274 | switch (a) {
275 | case "UTF8":
276 | case "UTF16BE":
277 | case "UTF16LE":
278 | break;
279 | default:
280 | throw Error("encoding must be UTF8, UTF16BE, or UTF16LE");
281 | }
282 | switch (c) {
283 | case "HEX":
284 | d = function (a, b, c) {
285 | var f = a.length, d, k, e, h, q;
286 | if (0 !== f % 2) {
287 | throw Error(
288 | "String of HEX type must be in byte increments");
289 | }
290 | b = b || [0];
291 | c = c || 0;
292 | q = c >>> 3;
293 | for (d = 0; d < f; d += 2) {
294 | k = parseInt(a.substr(d, 2), 16);
295 | if (isNaN(k)) {
296 | throw Error(
297 | "String of HEX type contains invalid characters");
298 | }
299 | h = (d >>> 1) + q;
300 | for (e = h >>> 2; b.length <= e;) {
301 | b.push(0);
302 | }
303 | b[e] |= k << 8 * (3 + h % 4 * -1)
304 | }
305 | return {value: b, binLen: 4 * f + c}
306 | };
307 | break;
308 | case "TEXT":
309 | d = function (c, b, d) {
310 | var f, n, k = 0, e, h, q, m, p, r;
311 | b = b || [0];
312 | d = d || 0;
313 | q = d >>> 3;
314 | if ("UTF8" === a) {
315 | for (r = 3, e = 0; e < c.length;
316 | e += 1) {
317 | for (f = c.charCodeAt(e), n = [], 128 > f ? n.push(f)
318 | : 2048 > f ? (n.push(192 | f >>> 6), n.push(128 | f & 63))
319 | : 55296 > f || 57344 <= f ? n.push(224 | f >>> 12, 128 | f
320 | >>> 6 & 63, 128 | f & 63) : (e += 1, f = 65536 + ((f
321 | & 1023) << 10 | c.charCodeAt(e) & 1023), n.push(240
322 | | f
323 | >>> 18, 128 | f >>> 12 & 63, 128 | f >>> 6 & 63, 128
324 | | f
325 | & 63)), h = 0; h < n.length; h += 1) {
326 | p = k +
327 | q;
328 | for (m = p >>> 2; b.length <= m;) {
329 | b.push(0);
330 | }
331 | b[m] |= n[h] << 8 * (r + p % 4 * -1);
332 | k += 1
333 | }
334 | }
335 | } else if ("UTF16BE" === a || "UTF16LE"
336 | === a) {
337 | for (r = 2, n = "UTF16LE" === a && !0 || "UTF16LE" !== a
338 | && !1, e = 0; e < c.length; e += 1) {
339 | f = c.charCodeAt(e);
340 | !0 === n && (h = f & 255, f = h << 8 | f >>> 8);
341 | p = k + q;
342 | for (m = p >>> 2; b.length <= m;) {
343 | b.push(0);
344 | }
345 | b[m] |= f << 8 * (r + p % 4 * -1);
346 | k += 2
347 | }
348 | }
349 | return {value: b, binLen: 8 * k + d}
350 | };
351 | break;
352 | case "B64":
353 | d = function (a, b, c) {
354 | var f = 0, d, k, e, h, q, m, p;
355 | if (-1 === a.search(/^[a-zA-Z0-9=+\/]+$/)) {
356 | throw Error(
357 | "Invalid character in base-64 string");
358 | }
359 | k = a.indexOf("=");
360 | a = a.replace(/\=/g,
361 | "");
362 | if (-1 !== k && k < a.length) {
363 | throw Error(
364 | "Invalid '=' found in base-64 string");
365 | }
366 | b = b || [0];
367 | c = c || 0;
368 | m = c >>> 3;
369 | for (k = 0; k < a.length; k += 4) {
370 | q = a.substr(k, 4);
371 | for (e = h = 0; e < q.length;
372 | e += 1) {
373 | d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(
374 | q[e]), h |= d << 18 - 6 * e;
375 | }
376 | for (e = 0; e < q.length - 1; e += 1) {
377 | p = f + m;
378 | for (d = p >>> 2; b.length <= d;) {
379 | b.push(0);
380 | }
381 | b[d] |= (h >>> 16 - 8 * e & 255) << 8 * (3 + p % 4 * -1);
382 | f += 1
383 | }
384 | }
385 | return {value: b, binLen: 8 * f + c}
386 | };
387 | break;
388 | case "BYTES":
389 | d = function (a, b, c) {
390 | var d, n, k, e, h;
391 | b = b || [0];
392 | c = c || 0;
393 | k = c >>> 3;
394 | for (n = 0; n < a.length; n +=
395 | 1) {
396 | d = a.charCodeAt(n), h = n + k, e = h >>> 2, b.length <= e
397 | && b.push(0), b[e] |= d << 8 * (3 + h % 4 * -1);
398 | }
399 | return {value: b, binLen: 8 * a.length + c}
400 | };
401 | break;
402 | case "ARRAYBUFFER":
403 | try {
404 | d = new ArrayBuffer(0)
405 | } catch (l) {
406 | throw Error("ARRAYBUFFER not supported by this environment");
407 | }
408 | d = function (a, b, c) {
409 | var d, n, k, e, h;
410 | b = b || [0];
411 | c = c || 0;
412 | n = c >>> 3;
413 | h = new Uint8Array(a);
414 | for (d = 0; d < a.byteLength; d += 1) {
415 | e = d + n, k = e >>> 2, b.length
416 | <= k && b.push(0), b[k] |= h[d] << 8 * (3 + e % 4 * -1);
417 | }
418 | return {value: b, binLen: 8 * a.byteLength + c}
419 | };
420 | break;
421 | default:
422 | throw Error("format must be HEX, TEXT, B64, BYTES, or ARRAYBUFFER");
423 | }
424 | return d
425 | }
426 |
427 | function r(c, a) {
428 | return c >>> a | c << 32 - a
429 | }
430 |
431 | function J(c, a, d) {
432 | return c & a ^ ~c & d
433 | }
434 |
435 | function K(c, a, d) {
436 | return c & a ^ c & d ^ a & d
437 | }
438 |
439 | function L(c) {
440 | return r(c, 2) ^ r(c, 13) ^ r(c, 22)
441 | }
442 |
443 | function M(c) {
444 | return r(c, 6) ^ r(c, 11) ^ r(c, 25)
445 | }
446 |
447 | function N(c) {
448 | return r(c, 7) ^ r(c, 18) ^ c >>> 3
449 | }
450 |
451 | function O(c) {
452 | return r(c, 17) ^ r(c, 19) ^ c >>> 10
453 | }
454 |
455 | function P(c, a) {
456 | var d = (c & 65535) + (a & 65535);
457 | return ((c >>> 16) + (a >>> 16) + (d >>> 16) & 65535) << 16 | d & 65535
458 | }
459 |
460 | function Q(c, a, d, l) {
461 | var b = (c & 65535) + (a & 65535) + (d & 65535) + (l & 65535);
462 | return ((c >>> 16) + (a >>> 16) + (d >>> 16) + (l >>> 16) + (b >>>
463 | 16) & 65535) << 16 | b & 65535
464 | }
465 |
466 | function R(c, a, d, l, b) {
467 | var g = (c & 65535) + (a & 65535) + (d & 65535) + (l & 65535) + (b & 65535);
468 | return ((c >>> 16) + (a >>> 16) + (d >>> 16) + (l >>> 16) + (b >>> 16) + (g
469 | >>> 16) & 65535) << 16 | g & 65535
470 | }
471 |
472 | function x(c) {
473 | var a = [], d;
474 | if (0 === c.lastIndexOf("SHA-", 0)) {
475 | switch (a = [3238371032, 914150663,
476 | 812702999, 4144912697, 4290775857, 1750603025, 1694076839,
477 | 3204075428], d = [1779033703, 3144134277, 1013904242, 2773480762,
478 | 1359893119, 2600822924, 528734635, 1541459225], c) {
479 | case "SHA-224":
480 | break;
481 | case "SHA-256":
482 | a = d;
483 | break;
484 | case "SHA-384":
485 | a = [new m, new m,
486 | new m, new m, new m, new m, new m, new m];
487 | break;
488 | case "SHA-512":
489 | a = [new m, new m, new m, new m, new m, new m, new m, new m];
490 | break;
491 | default:
492 | throw Error("Unknown SHA variant");
493 | }
494 | } else {
495 | throw Error("No SHA variants supported");
496 | }
497 | return a
498 | }
499 |
500 | function A(c, a, d) {
501 | var l, b, g, f, n, k, e, h, m, r, p, w, t, x, u, z, A, B, C, D, E, F,
502 | v = [], G;
503 | if ("SHA-224" === d || "SHA-256"
504 | === d) {
505 | r = 64, w = 1, F = Number, t = P, x = Q, u = R, z = N, A = O, B = L, C = M, E = K, D = J, G = H;
506 | } else {
507 | throw Error(
508 | "Unexpected error in SHA-2 implementation");
509 | }
510 | d = a[0];
511 | l = a[1];
512 | b = a[2];
513 | g = a[3];
514 | f = a[4];
515 | n = a[5];
516 | k = a[6];
517 | e = a[7];
518 | for (p =
519 | 0; p < r; p += 1) {
520 | 16 > p ? (m = p * w, h = c.length <= m ? 0
521 | : c[m], m = c.length <= m + 1 ? 0 : c[m + 1], v[p] = new F(h, m))
522 | : v[p] = x(A(v[p - 2]), v[p - 7], z(v[p - 15]), v[p - 16]), h = u(e,
523 | C(f), D(f, n, k), G[p], v[p]), m = t(B(d),
524 | E(d, l, b)), e = k, k = n, n = f, f = t(g,
525 | h), g = b, b = l, l = d, d = t(h, m);
526 | }
527 | a[0] = t(d, a[0]);
528 | a[1] = t(l, a[1]);
529 | a[2] = t(b, a[2]);
530 | a[3] = t(g, a[3]);
531 | a[4] = t(f, a[4]);
532 | a[5] = t(n, a[5]);
533 | a[6] = t(k, a[6]);
534 | a[7] = t(e, a[7]);
535 | return a
536 | }
537 |
538 | var H;
539 | H = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993,
540 | 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987,
541 | 1925078388, 2162078206,
542 | 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628,
543 | 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349,
544 | 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895,
545 | 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051,
546 | 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771,
547 | 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616,
548 | 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779,
549 | 1955562222, 2024104815, 2227730452, 2361852424, 2428436474,
550 | 2756734187, 3204031479, 3329325298];
551 | "function" === typeof define && define.amd ? define(function () {
552 | return w
553 | }) : "undefined" !== typeof exports ? ("undefined" !== typeof module
554 | && module.exports && (module.exports = w), exports = w) : I.jsSHA = w
555 | })(this);
556 |
--------------------------------------------------------------------------------
/src/lib/x64-core.js:
--------------------------------------------------------------------------------
1 | /*
2 | CryptoJS v3.1.2
3 | code.google.com/p/crypto-js
4 | (c) 2009-2013 by Jeff Mott. All rights reserved.
5 | code.google.com/p/crypto-js/wiki/License
6 | */
7 | (function (undefined) {
8 | // Shortcuts
9 | var C = CryptoJS;
10 | var C_lib = C.lib;
11 | var Base = C_lib.Base;
12 | var X32WordArray = C_lib.WordArray;
13 |
14 | /**
15 | * x64 namespace.
16 | */
17 | var C_x64 = C.x64 = {};
18 |
19 | /**
20 | * A 64-bit word.
21 | */
22 | var X64Word = C_x64.Word = Base.extend({
23 | /**
24 | * Initializes a newly created 64-bit word.
25 | *
26 | * @param {number} high The high 32 bits.
27 | * @param {number} low The low 32 bits.
28 | *
29 | * @example
30 | *
31 | * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
32 | */
33 | init: function (high, low) {
34 | this.high = high;
35 | this.low = low;
36 | }
37 |
38 | /**
39 | * Bitwise NOTs this word.
40 | *
41 | * @return {X64Word} A new x64-Word object after negating.
42 | *
43 | * @example
44 | *
45 | * var negated = x64Word.not();
46 | */
47 | // not: function () {
48 | // var high = ~this.high;
49 | // var low = ~this.low;
50 |
51 | // return X64Word.create(high, low);
52 | // },
53 |
54 | /**
55 | * Bitwise ANDs this word with the passed word.
56 | *
57 | * @param {X64Word} word The x64-Word to AND with this word.
58 | *
59 | * @return {X64Word} A new x64-Word object after ANDing.
60 | *
61 | * @example
62 | *
63 | * var anded = x64Word.and(anotherX64Word);
64 | */
65 | // and: function (word) {
66 | // var high = this.high & word.high;
67 | // var low = this.low & word.low;
68 |
69 | // return X64Word.create(high, low);
70 | // },
71 |
72 | /**
73 | * Bitwise ORs this word with the passed word.
74 | *
75 | * @param {X64Word} word The x64-Word to OR with this word.
76 | *
77 | * @return {X64Word} A new x64-Word object after ORing.
78 | *
79 | * @example
80 | *
81 | * var ored = x64Word.or(anotherX64Word);
82 | */
83 | // or: function (word) {
84 | // var high = this.high | word.high;
85 | // var low = this.low | word.low;
86 |
87 | // return X64Word.create(high, low);
88 | // },
89 |
90 | /**
91 | * Bitwise XORs this word with the passed word.
92 | *
93 | * @param {X64Word} word The x64-Word to XOR with this word.
94 | *
95 | * @return {X64Word} A new x64-Word object after XORing.
96 | *
97 | * @example
98 | *
99 | * var xored = x64Word.xor(anotherX64Word);
100 | */
101 | // xor: function (word) {
102 | // var high = this.high ^ word.high;
103 | // var low = this.low ^ word.low;
104 |
105 | // return X64Word.create(high, low);
106 | // },
107 |
108 | /**
109 | * Shifts this word n bits to the left.
110 | *
111 | * @param {number} n The number of bits to shift.
112 | *
113 | * @return {X64Word} A new x64-Word object after shifting.
114 | *
115 | * @example
116 | *
117 | * var shifted = x64Word.shiftL(25);
118 | */
119 | // shiftL: function (n) {
120 | // if (n < 32) {
121 | // var high = (this.high << n) | (this.low >>> (32 - n));
122 | // var low = this.low << n;
123 | // } else {
124 | // var high = this.low << (n - 32);
125 | // var low = 0;
126 | // }
127 |
128 | // return X64Word.create(high, low);
129 | // },
130 |
131 | /**
132 | * Shifts this word n bits to the right.
133 | *
134 | * @param {number} n The number of bits to shift.
135 | *
136 | * @return {X64Word} A new x64-Word object after shifting.
137 | *
138 | * @example
139 | *
140 | * var shifted = x64Word.shiftR(7);
141 | */
142 | // shiftR: function (n) {
143 | // if (n < 32) {
144 | // var low = (this.low >>> n) | (this.high << (32 - n));
145 | // var high = this.high >>> n;
146 | // } else {
147 | // var low = this.high >>> (n - 32);
148 | // var high = 0;
149 | // }
150 |
151 | // return X64Word.create(high, low);
152 | // },
153 |
154 | /**
155 | * Rotates this word n bits to the left.
156 | *
157 | * @param {number} n The number of bits to rotate.
158 | *
159 | * @return {X64Word} A new x64-Word object after rotating.
160 | *
161 | * @example
162 | *
163 | * var rotated = x64Word.rotL(25);
164 | */
165 | // rotL: function (n) {
166 | // return this.shiftL(n).or(this.shiftR(64 - n));
167 | // },
168 |
169 | /**
170 | * Rotates this word n bits to the right.
171 | *
172 | * @param {number} n The number of bits to rotate.
173 | *
174 | * @return {X64Word} A new x64-Word object after rotating.
175 | *
176 | * @example
177 | *
178 | * var rotated = x64Word.rotR(7);
179 | */
180 | // rotR: function (n) {
181 | // return this.shiftR(n).or(this.shiftL(64 - n));
182 | // },
183 |
184 | /**
185 | * Adds this word with the passed word.
186 | *
187 | * @param {X64Word} word The x64-Word to add with this word.
188 | *
189 | * @return {X64Word} A new x64-Word object after adding.
190 | *
191 | * @example
192 | *
193 | * var added = x64Word.add(anotherX64Word);
194 | */
195 | // add: function (word) {
196 | // var low = (this.low + word.low) | 0;
197 | // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
198 | // var high = (this.high + word.high + carry) | 0;
199 |
200 | // return X64Word.create(high, low);
201 | // }
202 | });
203 |
204 | /**
205 | * An array of 64-bit words.
206 | *
207 | * @property {Array} words The array of CryptoJS.x64.Word objects.
208 | * @property {number} sigBytes The number of significant bytes in this word array.
209 | */
210 | var X64WordArray = C_x64.WordArray = Base.extend({
211 | /**
212 | * Initializes a newly created word array.
213 | *
214 | * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
215 | * @param {number} sigBytes (Optional) The number of significant bytes in the words.
216 | *
217 | * @example
218 | *
219 | * var wordArray = CryptoJS.x64.WordArray.create();
220 | *
221 | * var wordArray = CryptoJS.x64.WordArray.create([
222 | * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
223 | * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
224 | * ]);
225 | *
226 | * var wordArray = CryptoJS.x64.WordArray.create([
227 | * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
228 | * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
229 | * ], 10);
230 | */
231 | init: function (words, sigBytes) {
232 | words = this.words = words || [];
233 |
234 | if (sigBytes != undefined) {
235 | this.sigBytes = sigBytes;
236 | } else {
237 | this.sigBytes = words.length * 8;
238 | }
239 | },
240 |
241 | /**
242 | * Converts this 64-bit word array to a 32-bit word array.
243 | *
244 | * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
245 | *
246 | * @example
247 | *
248 | * var x32WordArray = x64WordArray.toX32();
249 | */
250 | toX32: function () {
251 | // Shortcuts
252 | var x64Words = this.words;
253 | var x64WordsLength = x64Words.length;
254 |
255 | // Convert
256 | var x32Words = [];
257 | for (var i = 0; i < x64WordsLength; i++) {
258 | var x64Word = x64Words[i];
259 | x32Words.push(x64Word.high);
260 | x32Words.push(x64Word.low);
261 | }
262 |
263 | return X32WordArray.create(x32Words, this.sigBytes);
264 | },
265 |
266 | /**
267 | * Creates a copy of this word array.
268 | *
269 | * @return {X64WordArray} The clone.
270 | *
271 | * @example
272 | *
273 | * var clone = x64WordArray.clone();
274 | */
275 | clone: function () {
276 | var clone = Base.clone.call(this);
277 |
278 | // Clone "words" array
279 | var words = clone.words = this.words.slice(0);
280 |
281 | // Clone each X64Word object
282 | var wordsLength = words.length;
283 | for (var i = 0; i < wordsLength; i++) {
284 | words[i] = words[i].clone();
285 | }
286 |
287 | return clone;
288 | }
289 | });
290 | }());
291 |
--------------------------------------------------------------------------------
/src/protocol/core/TronInventoryItems_pb.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @fileoverview
3 | * @enhanceable
4 | * @suppress {messageConventions} JS Compiler reports an error if a variable or
5 | * field starts with 'MSG_' and isn't a translatable message.
6 | * @public
7 | */
8 | // GENERATED CODE -- DO NOT EDIT!
9 |
10 | var jspb = require('google-protobuf');
11 | var goog = jspb;
12 | var global = Function('return this')();
13 |
14 | goog.exportSymbol('proto.protocol.InventoryItems', null, global);
15 |
16 | /**
17 | * Generated by JsPbCodeGenerator.
18 | * @param {Array=} opt_data Optional initial data array, typically from a
19 | * server response, or constructed directly in Javascript. The array is used
20 | * in place and becomes part of the constructed object. It is not cloned.
21 | * If no data is provided, the constructed object will be empty, but still
22 | * valid.
23 | * @extends {jspb.Message}
24 | * @constructor
25 | */
26 | proto.protocol.InventoryItems = function(opt_data) {
27 | jspb.Message.initialize(this, opt_data, 0, -1, proto.protocol.InventoryItems.repeatedFields_, null);
28 | };
29 | goog.inherits(proto.protocol.InventoryItems, jspb.Message);
30 | if (goog.DEBUG && !COMPILED) {
31 | proto.protocol.InventoryItems.displayName = 'proto.protocol.InventoryItems';
32 | }
33 | /**
34 | * List of repeated fields within this message type.
35 | * @private {!Array}
36 | * @const
37 | */
38 | proto.protocol.InventoryItems.repeatedFields_ = [2];
39 |
40 |
41 |
42 | if (jspb.Message.GENERATE_TO_OBJECT) {
43 | /**
44 | * Creates an object representation of this proto suitable for use in Soy templates.
45 | * Field names that are reserved in JavaScript and will be renamed to pb_name.
46 | * To access a reserved field use, foo.pb_, eg, foo.pb_default.
47 | * For the list of reserved names please see:
48 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.
49 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
50 | * for transitional soy proto support: http://goto/soy-param-migration
51 | * @return {!Object}
52 | */
53 | proto.protocol.InventoryItems.prototype.toObject = function(opt_includeInstance) {
54 | return proto.protocol.InventoryItems.toObject(opt_includeInstance, this);
55 | };
56 |
57 |
58 | /**
59 | * Static version of the {@see toObject} method.
60 | * @param {boolean|undefined} includeInstance Whether to include the JSPB
61 | * instance for transitional soy proto support:
62 | * http://goto/soy-param-migration
63 | * @param {!proto.protocol.InventoryItems} msg The msg instance to transform.
64 | * @return {!Object}
65 | * @suppress {unusedLocalVariables} f is only used for nested messages
66 | */
67 | proto.protocol.InventoryItems.toObject = function(includeInstance, msg) {
68 | var f, obj = {
69 | type: jspb.Message.getFieldWithDefault(msg, 1, 0),
70 | itemsList: msg.getItemsList_asB64()
71 | };
72 |
73 | if (includeInstance) {
74 | obj.$jspbMessageInstance = msg;
75 | }
76 | return obj;
77 | };
78 | }
79 |
80 |
81 | /**
82 | * Deserializes binary data (in protobuf wire format).
83 | * @param {jspb.ByteSource} bytes The bytes to deserialize.
84 | * @return {!proto.protocol.InventoryItems}
85 | */
86 | proto.protocol.InventoryItems.deserializeBinary = function(bytes) {
87 | var reader = new jspb.BinaryReader(bytes);
88 | var msg = new proto.protocol.InventoryItems;
89 | return proto.protocol.InventoryItems.deserializeBinaryFromReader(msg, reader);
90 | };
91 |
92 |
93 | /**
94 | * Deserializes binary data (in protobuf wire format) from the
95 | * given reader into the given message object.
96 | * @param {!proto.protocol.InventoryItems} msg The message object to deserialize into.
97 | * @param {!jspb.BinaryReader} reader The BinaryReader to use.
98 | * @return {!proto.protocol.InventoryItems}
99 | */
100 | proto.protocol.InventoryItems.deserializeBinaryFromReader = function(msg, reader) {
101 | while (reader.nextField()) {
102 | if (reader.isEndGroup()) {
103 | break;
104 | }
105 | var field = reader.getFieldNumber();
106 | switch (field) {
107 | case 1:
108 | var value = /** @type {number} */ (reader.readInt32());
109 | msg.setType(value);
110 | break;
111 | case 2:
112 | var value = /** @type {!Uint8Array} */ (reader.readBytes());
113 | msg.addItems(value);
114 | break;
115 | default:
116 | reader.skipField();
117 | break;
118 | }
119 | }
120 | return msg;
121 | };
122 |
123 |
124 | /**
125 | * Serializes the message to binary data (in protobuf wire format).
126 | * @return {!Uint8Array}
127 | */
128 | proto.protocol.InventoryItems.prototype.serializeBinary = function() {
129 | var writer = new jspb.BinaryWriter();
130 | proto.protocol.InventoryItems.serializeBinaryToWriter(this, writer);
131 | return writer.getResultBuffer();
132 | };
133 |
134 |
135 | /**
136 | * Serializes the given message to binary data (in protobuf wire
137 | * format), writing to the given BinaryWriter.
138 | * @param {!proto.protocol.InventoryItems} message
139 | * @param {!jspb.BinaryWriter} writer
140 | * @suppress {unusedLocalVariables} f is only used for nested messages
141 | */
142 | proto.protocol.InventoryItems.serializeBinaryToWriter = function(message, writer) {
143 | var f = undefined;
144 | f = message.getType();
145 | if (f !== 0) {
146 | writer.writeInt32(
147 | 1,
148 | f
149 | );
150 | }
151 | f = message.getItemsList_asU8();
152 | if (f.length > 0) {
153 | writer.writeRepeatedBytes(
154 | 2,
155 | f
156 | );
157 | }
158 | };
159 |
160 |
161 | /**
162 | * optional int32 type = 1;
163 | * @return {number}
164 | */
165 | proto.protocol.InventoryItems.prototype.getType = function() {
166 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));
167 | };
168 |
169 |
170 | /** @param {number} value */
171 | proto.protocol.InventoryItems.prototype.setType = function(value) {
172 | jspb.Message.setProto3IntField(this, 1, value);
173 | };
174 |
175 |
176 | /**
177 | * repeated bytes items = 2;
178 | * @return {!(Array|Array)}
179 | */
180 | proto.protocol.InventoryItems.prototype.getItemsList = function() {
181 | return /** @type {!(Array|Array)} */ (jspb.Message.getRepeatedField(this, 2));
182 | };
183 |
184 |
185 | /**
186 | * repeated bytes items = 2;
187 | * This is a type-conversion wrapper around `getItemsList()`
188 | * @return {!Array.}
189 | */
190 | proto.protocol.InventoryItems.prototype.getItemsList_asB64 = function() {
191 | return /** @type {!Array.} */ (jspb.Message.bytesListAsB64(
192 | this.getItemsList()));
193 | };
194 |
195 |
196 | /**
197 | * repeated bytes items = 2;
198 | * Note that Uint8Array is not supported on all browsers.
199 | * @see http://caniuse.com/Uint8Array
200 | * This is a type-conversion wrapper around `getItemsList()`
201 | * @return {!Array.}
202 | */
203 | proto.protocol.InventoryItems.prototype.getItemsList_asU8 = function() {
204 | return /** @type {!Array.} */ (jspb.Message.bytesListAsU8(
205 | this.getItemsList()));
206 | };
207 |
208 |
209 | /** @param {!(Array|Array)} value */
210 | proto.protocol.InventoryItems.prototype.setItemsList = function(value) {
211 | jspb.Message.setField(this, 2, value || []);
212 | };
213 |
214 |
215 | /**
216 | * @param {!(string|Uint8Array)} value
217 | * @param {number=} opt_index
218 | */
219 | proto.protocol.InventoryItems.prototype.addItems = function(value, opt_index) {
220 | jspb.Message.addToRepeatedField(this, 2, value, opt_index);
221 | };
222 |
223 |
224 | proto.protocol.InventoryItems.prototype.clearItemsList = function() {
225 | this.setItemsList([]);
226 | };
227 |
228 |
229 | goog.object.extend(exports, proto.protocol);
230 |
--------------------------------------------------------------------------------
/src/signer/privateKeySigner.js:
--------------------------------------------------------------------------------
1 | const {signTransaction} = require("../utils/crypto");
2 |
3 |
4 | class PrivateKeySigner {
5 | constructor(privateKey) {
6 | this.privateKey = privateKey;
7 | }
8 |
9 | async signTransaction(transaction) {
10 | return signTransaction(this.privateKey, transaction);
11 | }
12 | }
13 |
14 | module.exports = PrivateKeySigner;
15 |
--------------------------------------------------------------------------------
/src/utils/account.js:
--------------------------------------------------------------------------------
1 | const byteArray2hexStr = require("./bytes").byteArray2hexStr;
2 | const base64EncodeToString = require("../lib/code").base64EncodeToString;
3 | const {getBase58CheckAddress, genPriKey, getAddressFromPriKey} = require("./crypto");
4 |
5 | /**
6 | * Generate a new account
7 | */
8 | function generateAccount() {
9 | let priKeyBytes = genPriKey();
10 | let addressBytes = getAddressFromPriKey(priKeyBytes);
11 | let address = getBase58CheckAddress(addressBytes);
12 | let password = base64EncodeToString(priKeyBytes);
13 | let privateKey = byteArray2hexStr(priKeyBytes);
14 |
15 | return {
16 | privateKey,
17 | address,
18 | password,
19 | }
20 | }
21 |
22 | module.exports = {
23 | generateAccount,
24 | };
25 |
--------------------------------------------------------------------------------
/src/utils/address.js:
--------------------------------------------------------------------------------
1 | const ADDRESS_SIZE = 34;
2 | const ADDRESS_PREFIX = "41";
3 | const ADDRESS_PREFIX_BYTE = 0x41;
4 |
5 | module.exports = {
6 | ADDRESS_SIZE,
7 | ADDRESS_PREFIX,
8 | ADDRESS_PREFIX_BYTE,
9 | };
10 |
--------------------------------------------------------------------------------
/src/utils/base64.js:
--------------------------------------------------------------------------------
1 |
2 | exports.Base64 = function() {
3 |
4 | // private property
5 | var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
6 |
7 | // public method for encoding
8 | this.encode = function (input) {
9 | var output = "";
10 | var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
11 | var i = 0;
12 | // input = _utf8_encode(input);
13 | while (i < input.length) {
14 | chr1 = input.charCodeAt(i++);
15 | chr2 = input.charCodeAt(i++);
16 | chr3 = input.charCodeAt(i++);
17 | enc1 = chr1 >> 2;
18 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
19 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
20 | enc4 = chr3 & 63;
21 | if (isNaN(chr2)) {
22 | enc3 = enc4 = 64;
23 | } else if (isNaN(chr3)) {
24 | enc4 = 64;
25 | }
26 | output = output +
27 | _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
28 | _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
29 | }
30 | return output;
31 | }
32 |
33 | // public method for encoding
34 | this.encodeIgnoreUtf8 = function (inputBytes) {
35 | var output = "";
36 | var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
37 | var i = 0;
38 | // input = _utf8_encode(input);
39 | while (i < inputBytes.length) {
40 | chr1 = inputBytes[i++];
41 | chr2 = inputBytes[i++];
42 | chr3 = inputBytes[i++];
43 | enc1 = chr1 >> 2;
44 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
45 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
46 | enc4 = chr3 & 63;
47 | if (isNaN(chr2)) {
48 | enc3 = enc4 = 64;
49 | } else if (isNaN(chr3)) {
50 | enc4 = 64;
51 | }
52 | output = output +
53 | _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
54 | _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
55 | }
56 | return output;
57 | }
58 |
59 | // public method for decoding
60 | this.decode = function (input) {
61 | var output = "";
62 | var chr1, chr2, chr3;
63 | var enc1, enc2, enc3, enc4;
64 | var i = 0;
65 | input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
66 | while (i < input.length) {
67 | enc1 = _keyStr.indexOf(input.charAt(i++));
68 | enc2 = _keyStr.indexOf(input.charAt(i++));
69 | enc3 = _keyStr.indexOf(input.charAt(i++));
70 | enc4 = _keyStr.indexOf(input.charAt(i++));
71 | chr1 = (enc1 << 2) | (enc2 >> 4);
72 | chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
73 | chr3 = ((enc3 & 3) << 6) | enc4;
74 | output = output + String.fromCharCode(chr1);
75 | if (enc3 != 64) {
76 | output = output + String.fromCharCode(chr2);
77 | }
78 | if (enc4 != 64) {
79 | output = output + String.fromCharCode(chr3);
80 | }
81 | }
82 | output = _utf8_decode(output);
83 | return output;
84 | }
85 |
86 | // public method for decoding
87 | this.decodeToByteArray = function (input) {
88 | var output = "";
89 | var chr1, chr2, chr3;
90 | var enc1, enc2, enc3, enc4;
91 | var i = 0;
92 | input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
93 | while (i < input.length) {
94 | enc1 = _keyStr.indexOf(input.charAt(i++));
95 | enc2 = _keyStr.indexOf(input.charAt(i++));
96 | enc3 = _keyStr.indexOf(input.charAt(i++));
97 | enc4 = _keyStr.indexOf(input.charAt(i++));
98 | chr1 = (enc1 << 2) | (enc2 >> 4);
99 | chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
100 | chr3 = ((enc3 & 3) << 6) | enc4;
101 | output = output + String.fromCharCode(chr1);
102 | if (enc3 != 64) {
103 | output = output + String.fromCharCode(chr2);
104 | }
105 | if (enc4 != 64) {
106 | output = output + String.fromCharCode(chr3);
107 | }
108 | }
109 | var outBytes = _out2ByteArray(output);
110 | return outBytes;
111 | }
112 |
113 | // private method for UTF-8 decoding
114 | var _out2ByteArray = function (utftext) {
115 | var byteArray = new Array(utftext.length)
116 | var i = 0;
117 | var c = c1 = c2 = 0;
118 | while (i < utftext.length) {
119 | c = utftext.charCodeAt(i);
120 | byteArray[i] = c;
121 | i++;
122 | }
123 | return byteArray;
124 | }
125 |
126 | // private method for UTF-8 encoding
127 | var _utf8_encode = function (string) {
128 | string = string.replace(/\r\n/g, "\n");
129 | var utftext = "";
130 | for (var n = 0; n < string.length; n++) {
131 | var c = string.charCodeAt(n);
132 | if (c < 128) {
133 | utftext += String.fromCharCode(c);
134 | } else if ((c > 127) && (c < 2048)) {
135 | utftext += String.fromCharCode((c >> 6) | 192);
136 | utftext += String.fromCharCode((c & 63) | 128);
137 | } else {
138 | utftext += String.fromCharCode((c >> 12) | 224);
139 | utftext += String.fromCharCode(((c >> 6) & 63) | 128);
140 | utftext += String.fromCharCode((c & 63) | 128);
141 | }
142 |
143 | }
144 | return utftext;
145 | }
146 |
147 | // private method for UTF-8 decoding
148 | var _utf8_decode = function (utftext) {
149 | var string = "";
150 | var i = 0;
151 | var c = c1 = c2 = 0;
152 | while (i < utftext.length) {
153 | c = utftext.charCodeAt(i);
154 | if (c < 128) {
155 | string += String.fromCharCode(c);
156 | i++;
157 | } else if ((c > 191) && (c < 224)) {
158 | c2 = utftext.charCodeAt(i + 1);
159 | string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
160 | i += 2;
161 | } else {
162 | c2 = utftext.charCodeAt(i + 1);
163 | c3 = utftext.charCodeAt(i + 2);
164 | string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3
165 | & 63));
166 | i += 3;
167 | }
168 | }
169 | return string;
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/src/utils/bytes.js:
--------------------------------------------------------------------------------
1 | const {Base64} = require("./base64");
2 |
3 | /* Convert a byte to string */
4 | function byte2hexStr(byte) {
5 | var hexByteMap = "0123456789ABCDEF";
6 | var str = "";
7 | str += hexByteMap.charAt(byte >> 4);
8 | str += hexByteMap.charAt(byte & 0x0f);
9 | return str;
10 | }
11 |
12 | /**
13 | * Converts a byte array to string
14 | *
15 | * @param {Uint8Array} arr byte array
16 | * @returns {string}
17 | */
18 | function bytesToString(arr) {
19 | if (typeof arr === 'string') {
20 | return arr;
21 | }
22 | let str = '',
23 | _arr = arr;
24 | for (let i = 0; i < _arr.length; i++) {
25 | let one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);
26 | if (v && one.length === 8) {
27 | let bytesLength = v[0].length;
28 | let store = _arr[i].toString(2).slice(7 - bytesLength);
29 | for (let st = 1; st < bytesLength; st++) {
30 | store += _arr[st + i].toString(2).slice(2);
31 | }
32 | str += String.fromCharCode(parseInt(store, 2));
33 | i += bytesLength - 1;
34 | } else {
35 | str += String.fromCharCode(_arr[i]);
36 | }
37 | }
38 | return str;
39 | }
40 |
41 | /**
42 | * Converts a hex string to a decoded string
43 | *
44 | * @param {string} hex
45 | * @returns {string}
46 | */
47 | function hextoString(hex) {
48 | let arr = hex.split("");
49 | let out = "";
50 | for (let i = 0; i < arr.length / 2; i++) {
51 | let tmp = "0x" + arr[i * 2] + arr[i * 2 + 1];
52 | out += String.fromCharCode(tmp);
53 | }
54 | return out;
55 | }
56 |
57 | function base64DecodeFromString(string64) {
58 | return new Base64().decodeToByteArray(string64);
59 | }
60 |
61 | function byteArray2hexStr(byteArray) {
62 | let str = "";
63 | for (let i = 0; i < (byteArray.length); i++) {
64 | str += byte2hexStr(byteArray[i]);
65 | }
66 | return str;
67 | }
68 |
69 |
70 | module.exports = {
71 | byteArray2hexStr,
72 | hextoString,
73 | base64DecodeFromString,
74 | bytesToString,
75 | byte2hexStr
76 | };
77 |
--------------------------------------------------------------------------------
/src/utils/crypto.js:
--------------------------------------------------------------------------------
1 | const {ADDRESS_PREFIX, ADDRESS_PREFIX_BYTE} = require("./address");
2 | const base64EncodeToString = require("../lib/code").base64EncodeToString;
3 | const {base64DecodeFromString, hexStr2byteArray} = require("../lib/code");
4 | const {encode58, decode58} = require("../lib/base58");
5 | const EC = require('elliptic').ec;
6 | const { keccak256 } = require('js-sha3');
7 | const jsSHA = require("../lib/sha256");
8 | const ADDRESS_SIZE = require("./address").ADDRESS_SIZE;
9 | const { byte2hexStr, byteArray2hexStr } = require("./bytes");
10 |
11 | /**
12 | * Sign A Transaction by priKey.
13 | * signature is 65 bytes, r[32] || s[32] || id[1](<27)
14 | * @returns a Transaction object signed
15 | * @param priKeyBytes: privateKey for ECC
16 | * @param transaction: a Transaction object unSigned
17 | */
18 | function signTransaction(priKeyBytes, transaction) {
19 |
20 | if (typeof priKeyBytes === 'string') {
21 | priKeyBytes = hexStr2byteArray(priKeyBytes);
22 | }
23 |
24 | let raw = transaction.getRawData();
25 | let rawBytes = raw.serializeBinary();
26 | let hashBytes = SHA256(rawBytes);
27 | let signBytes = ECKeySign(hashBytes, priKeyBytes);
28 | let uint8Array = new Uint8Array(signBytes);
29 | let count = raw.getContractList().length;
30 | for (let i = 0; i < count; i++) {
31 | transaction.addSignature(uint8Array);
32 | }
33 |
34 | return {
35 | transaction,
36 | hex: byteArray2hexStr(transaction.serializeBinary()),
37 | };
38 | }
39 |
40 | function arrayToBase64String(a) {
41 | return btoa(String.fromCharCode(...a));
42 | }
43 |
44 | function signBytes(privateKey, contents) {
45 |
46 | if (typeof privateKey === 'string') {
47 | privateKey = hexStr2byteArray(privateKey);
48 | }
49 |
50 | let hashBytes = SHA256(contents);
51 | let signBytes = ECKeySign(hashBytes, privateKey);
52 |
53 | return signBytes;
54 | }
55 |
56 | //return bytes of rowdata, use to sign.
57 | function getRowBytesFromTransactionBase64(base64Data) {
58 | let bytesDecode = base64DecodeFromString(base64Data);
59 | let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode);
60 | let raw = transaction.getRawData();
61 | return raw.serializeBinary();
62 | }
63 |
64 | //gen Ecc priKey for bytes
65 | function genPriKey() {
66 | let ec = new EC('secp256k1');
67 | let key = ec.genKeyPair();
68 | let priKey = key.getPrivate();
69 | let priKeyHex = priKey.toString('hex');
70 | while (priKeyHex.length < 64) {
71 | priKeyHex = "0" + priKeyHex;
72 | }
73 |
74 | return hexStr2byteArray(priKeyHex);
75 | }
76 |
77 | //return address by bytes, pubBytes is byte[]
78 | function computeAddress(pubBytes) {
79 | if (pubBytes.length === 65) {
80 | pubBytes = pubBytes.slice(1);
81 | }
82 |
83 | var hash = keccak256(pubBytes).toString();
84 | var addressHex = hash.substring(24);
85 | addressHex = ADDRESS_PREFIX + addressHex;
86 | return hexStr2byteArray(addressHex);
87 | }
88 |
89 | //return address by bytes, priKeyBytes is byte[]
90 | function getAddressFromPriKey(priKeyBytes) {
91 | let pubBytes = getPubKeyFromPriKey(priKeyBytes);
92 | return computeAddress(pubBytes);
93 | }
94 |
95 | //return address by Base58Check String,
96 | function getBase58CheckAddress(addressBytes) {
97 | var hash0 = SHA256(addressBytes);
98 | var hash1 = SHA256(hash0);
99 | var checkSum = hash1.slice(0, 4);
100 | checkSum = addressBytes.concat(checkSum);
101 | return encode58(checkSum);
102 | }
103 |
104 | function decode58Check(addressStr) {
105 |
106 | var decodeCheck = decode58(addressStr);
107 | if (decodeCheck.length <= 4) {
108 | console.error("ERROR CHECK");
109 | return null;
110 | }
111 |
112 | var decodeData = decodeCheck.slice(0, decodeCheck.length - 4);
113 | var hash0 = SHA256(decodeData);
114 | var hash1 = SHA256(hash0);
115 |
116 | if (hash1[0] === decodeCheck[decodeData.length] &&
117 | hash1[1] === decodeCheck[decodeData.length + 1] &&
118 | hash1[2] === decodeCheck[decodeData.length + 2] &&
119 | hash1[3] === decodeCheck[decodeData.length + 3]) {
120 | return decodeData;
121 | }
122 |
123 | return null;
124 | }
125 |
126 | function isAddressValid(base58Str) {
127 | try {
128 | if (typeof(base58Str) !== 'string') {
129 | return false;
130 | }
131 | if (base58Str.length !== ADDRESS_SIZE) {
132 | return false;
133 | }
134 | var address = decode58(base58Str);
135 | if (address.length !== 25) {
136 | return false;
137 | }
138 | if (address[0] !== ADDRESS_PREFIX_BYTE) {
139 | return false;
140 | }
141 | var checkSum = address.slice(21);
142 | address = address.slice(0, 21);
143 | var hash0 = SHA256(address);
144 | var hash1 = SHA256(hash0);
145 | var checkSum1 = hash1.slice(0, 4);
146 | if (checkSum[0] == checkSum1[0] && checkSum[1] == checkSum1[1] && checkSum[2]
147 | == checkSum1[2] && checkSum[3] == checkSum1[3]
148 | ) {
149 | return true
150 | }
151 | } catch(e) {
152 | // ignore
153 | }
154 |
155 | return false;
156 | }
157 |
158 | //return address by Base58Check String, priKeyBytes is base64String
159 | function getBase58CheckAddressFromPriKeyBase64String(priKeyBase64String) {
160 | var priKeyBytes = base64DecodeFromString(priKeyBase64String);
161 | var pubBytes = getPubKeyFromPriKey(priKeyBytes);
162 | var addressBytes = computeAddress(pubBytes);
163 | return getBase58CheckAddress(addressBytes);
164 | }
165 |
166 | //return address by String, priKeyBytes is base64String
167 | function getHexStrAddressFromPriKeyBase64String(priKeyBase64String) {
168 | let priKeyBytes = base64DecodeFromString(priKeyBase64String);
169 | let pubBytes = getPubKeyFromPriKey(priKeyBytes);
170 | let addressBytes = computeAddress(pubBytes);
171 | let addressHex = byteArray2hexStr(addressBytes);
172 | return addressHex;
173 | }
174 | //return address by String, priKeyBytes is base64String
175 | function getAddressFromPriKeyBase64String(priKeyBase64String) {
176 | let priKeyBytes = base64DecodeFromString(priKeyBase64String);
177 | let pubBytes = getPubKeyFromPriKey(priKeyBytes);
178 | let addressBytes = computeAddress(pubBytes);
179 | let addressBase64 = base64EncodeToString(addressBytes);
180 | return addressBase64;
181 | }
182 |
183 | //return pubkey by 65 bytes, priKeyBytes is byte[]
184 | function getPubKeyFromPriKey(priKeyBytes) {
185 | var ec = new EC('secp256k1');
186 | var key = ec.keyFromPrivate(priKeyBytes, 'bytes');
187 | var pubkey = key.getPublic();
188 | var x = pubkey.x;
189 | var y = pubkey.y;
190 | var xHex = x.toString('hex');
191 | while (xHex.length < 64) {
192 | xHex = "0" + xHex;
193 | }
194 | var yHex = y.toString('hex');
195 | while (yHex.length < 64) {
196 | yHex = "0" + yHex;
197 | }
198 | var pubkeyHex = "04" + xHex + yHex;
199 | var pubkeyBytes = hexStr2byteArray(pubkeyHex);
200 | return pubkeyBytes;
201 | }
202 |
203 | //return sign by 65 bytes r s id. id < 27
204 | function ECKeySign(hashBytes, priKeyBytes) {
205 | let ec = new EC('secp256k1');
206 | let key = ec.keyFromPrivate(priKeyBytes, 'bytes');
207 | let signature = key.sign(hashBytes);
208 | let r = signature.r;
209 | let s = signature.s;
210 | let id = signature.recoveryParam;
211 |
212 | let rHex = r.toString('hex');
213 | while (rHex.length < 64) {
214 | rHex = "0" + rHex;
215 | }
216 | let sHex = s.toString('hex');
217 | while (sHex.length < 64) {
218 | sHex = "0" + sHex;
219 | }
220 | let idHex = byte2hexStr(id);
221 | let signHex = rHex + sHex + idHex;
222 | return hexStr2byteArray(signHex);
223 | }
224 |
225 | //toDO:
226 | //return 32 bytes
227 | function SHA256(msgBytes) {
228 | let shaObj = new jsSHA("SHA-256", "HEX");
229 | let msgHex = byteArray2hexStr(msgBytes);
230 | shaObj.update(msgHex);
231 | let hashHex = shaObj.getHash("HEX");
232 | return hexStr2byteArray(hashHex);
233 | }
234 |
235 | function passwordToAddress(password) {
236 | let com_priKeyBytes = base64DecodeFromString(password);
237 | let com_addressBytes = getAddressFromPriKey(com_priKeyBytes);
238 | return getBase58CheckAddress(com_addressBytes);
239 | }
240 |
241 | function pkToAddress(privateKey) {
242 | let com_priKeyBytes = hexStr2byteArray(privateKey);
243 | let com_addressBytes = getAddressFromPriKey(com_priKeyBytes);
244 | return getBase58CheckAddress(com_addressBytes);
245 | }
246 |
247 | module.exports = {
248 | signTransaction,
249 | passwordToAddress,
250 | genPriKey,
251 | getAddressFromPriKey,
252 | getPubKeyFromPriKey,
253 | getBase58CheckAddress,
254 | isAddressValid,
255 | getBase58CheckAddressFromPriKeyBase64String,
256 | pkToAddress,
257 | decode58Check,
258 | signBytes,
259 | };
260 |
--------------------------------------------------------------------------------
/src/utils/transactionBuilder.js:
--------------------------------------------------------------------------------
1 | const decode58Check = require("./crypto").decode58Check;
2 | const { Block, Transaction, Account } = require("../protocol/core/Tron_pb");
3 | const google_protobuf_any_pb = require('google-protobuf/google/protobuf/any_pb.js');
4 | const { encodeString } = require("../lib/code");
5 | const { byte2hexStr, byteArray2hexStr } = require("./bytes");
6 |
7 | const {
8 | TransferContract,
9 | TransferAssetContract,
10 | AccountUpdateContract,
11 | VoteWitnessContract,
12 | ParticipateAssetIssueContract,
13 | AssetIssueContract,
14 | FreezeBalanceContract,
15 | UnfreezeBalanceContract,
16 | WitnessUpdateContract,
17 | WithdrawBalanceContract,
18 | WitnessCreateContract,
19 | UnfreezeAssetContract,
20 | ExchangeCreateContract,
21 | ExchangeInjectContract,
22 | ExchangeWithdrawContract,
23 | ExchangeTransactionContract,
24 | UpdateAssetContract,
25 | TriggerSmartContract,
26 | AccountPermissionUpdateContract,
27 | } = require("../protocol/core/Contract_pb");
28 |
29 | const fromHexString = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
30 |
31 | function parameterValue2hexStr(message, contractType, typeName) {
32 | let anyValue = new google_protobuf_any_pb.Any();
33 | return byteArray2hexStr(message.serializeBinary());
34 | }
35 |
36 |
37 | function buildTransferHexStr(token, from, to, amount) {
38 | if (token === '_') {
39 | let transferContract = new TransferContract();
40 | transferContract.setToAddress(Uint8Array.from(decode58Check(to)));
41 | transferContract.setOwnerAddress(Uint8Array.from(decode58Check(from)));
42 | transferContract.setAmount(amount);
43 | return parameterValue2hexStr(
44 | transferContract,
45 | Transaction.Contract.ContractType.TRANSFERCONTRACT,
46 | "TransferContract");
47 | } else {
48 | let transferContract = new TransferAssetContract();
49 | transferContract.setToAddress(Uint8Array.from(decode58Check(to)));
50 | transferContract.setOwnerAddress(Uint8Array.from(decode58Check(from)));
51 | transferContract.setAmount(amount);
52 | transferContract.setAssetName(encodeString(token));
53 | return parameterValue2hexStr(
54 | transferContract,
55 | Transaction.Contract.ContractType.TRANSFERASSETCONTRACT,
56 | "TransferAssetContract");
57 | }
58 | }
59 |
60 | function buildTransferContract(message, contractType, typeName, permissionId) {
61 | let anyValue = new google_protobuf_any_pb.Any();
62 | anyValue.pack(message.serializeBinary(), "protocol." + typeName);
63 | let contract = new Transaction.Contract();
64 | contract.setType(contractType);
65 | contract.setParameter(anyValue);
66 | if(permissionId){
67 | contract.setPermissionId(permissionId);
68 | }
69 | let raw = new Transaction.raw();
70 | raw.addContract(contract);
71 | // raw.setTimestamp(new Date().getTime() * 1000000);
72 | let transaction = new Transaction();
73 | transaction.setRawData(raw);
74 | return transaction;
75 | }
76 |
77 |
78 |
79 | function buildTransferTransaction(token, from, to, amount) {
80 |
81 | if (token === '_') {
82 |
83 | let transferContract = new TransferContract();
84 | transferContract.setToAddress(Uint8Array.from(decode58Check(to)));
85 | transferContract.setOwnerAddress(Uint8Array.from(decode58Check(from)));
86 | transferContract.setAmount(amount);
87 |
88 | return buildTransferContract(
89 | transferContract,
90 | Transaction.Contract.ContractType.TRANSFERCONTRACT,
91 | "TransferContract");
92 | } else {
93 |
94 | let transferContract = new TransferAssetContract();
95 | transferContract.setToAddress(Uint8Array.from(decode58Check(to)));
96 | transferContract.setOwnerAddress(Uint8Array.from(decode58Check(from)));
97 | transferContract.setAmount(amount);
98 | transferContract.setAssetName(encodeString(token));
99 |
100 | return buildTransferContract(
101 | transferContract,
102 | Transaction.Contract.ContractType.TRANSFERASSETCONTRACT,
103 | "TransferAssetContract");
104 | }
105 | }
106 |
107 | function buildAccountUpdate(address, name) {
108 | let contract = new AccountUpdateContract();
109 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
110 | contract.setAccountName(encodeString(name));
111 |
112 | return buildTransferContract(
113 | contract,
114 | Transaction.Contract.ContractType.ACCOUNTUPDATECONTRACT,
115 | "AccountUpdateContract");
116 | }
117 |
118 | function buildAssetUpdate(address, description, url) {
119 | let contract = new UpdateAssetContract();
120 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
121 | contract.setDescription(encodeString(description));
122 | contract.setUrl(encodeString(url));
123 |
124 | return buildTransferContract(
125 | contract,
126 | Transaction.Contract.ContractType.UPDATEASSETCONTRACT,
127 | "UpdateAssetContract");
128 | }
129 |
130 | function buildWitnessCreate(address, url) {
131 | let contract = new WitnessCreateContract();
132 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
133 | contract.setUrl(encodeString(url));
134 |
135 | return buildTransferContract(
136 | contract,
137 | Transaction.Contract.ContractType.WITNESSCREATECONTRACT,
138 | "WitnessCreateContract");
139 | }
140 |
141 | function buildWitnessUpdate(address, url) {
142 | let contract = new WitnessUpdateContract();
143 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
144 | contract.setUpdateUrl(encodeString(url));
145 |
146 | return buildTransferContract(
147 | contract,
148 | Transaction.Contract.ContractType.WITNESSUPDATECONTRACT,
149 | "WitnessUpdateContract");
150 | }
151 |
152 | function buildWithdrawBalance(address) {
153 | let contract = new WithdrawBalanceContract();
154 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
155 |
156 | return buildTransferContract(
157 | contract,
158 | Transaction.Contract.ContractType.WITHDRAWBALANCECONTRACT,
159 | "WithdrawBalanceContract");
160 | }
161 |
162 | function buildVote(address, votes) {
163 | let contract = new VoteWitnessContract();
164 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
165 |
166 | for (let address of Object.keys(votes)) {
167 | let vote = new VoteWitnessContract.Vote();
168 | vote.setVoteAddress(Uint8Array.from(decode58Check(address)));
169 | let numberOfVotes = parseInt(votes[address]);
170 | if (isNaN(numberOfVotes) || numberOfVotes <= 0) {
171 | continue;
172 | }
173 | vote.setVoteCount(numberOfVotes);
174 | contract.addVotes(vote);
175 | }
176 |
177 | return buildTransferContract(
178 | contract,
179 | Transaction.Contract.ContractType.VOTEWITNESSCONTRACT,
180 | "VoteWitnessContract");
181 | }
182 |
183 |
184 | function buildAssetParticipate(address, issuerAddress, token, amount) {
185 | let contract = new ParticipateAssetIssueContract();
186 |
187 | contract.setToAddress(Uint8Array.from(decode58Check(issuerAddress)));
188 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
189 | contract.setAssetName(encodeString(token));
190 | contract.setAmount(amount);
191 |
192 | return buildTransferContract(
193 | contract,
194 | Transaction.Contract.ContractType.PARTICIPATEASSETISSUECONTRACT,
195 | "ParticipateAssetIssueContract");
196 | }
197 |
198 | function buildAssetIssue(options) {
199 |
200 | let contract = new AssetIssueContract();
201 | contract.setOwnerAddress(Uint8Array.from(decode58Check(options.address)));
202 | contract.setName(encodeString(options.name));
203 | contract.setAbbr(encodeString(options.shortName));
204 | contract.setTotalSupply(options.totalSupply);
205 | contract.setNum(options.num);
206 | contract.setEndTime(Date.parse(options.endTime));
207 | contract.setStartTime(Date.parse(options.startTime));
208 | contract.setTrxNum(options.trxNum);
209 | contract.setPrecision(options.precision);
210 | contract.setDescription(encodeString(options.description));
211 | contract.setUrl(encodeString(options.url));
212 | contract.setPublicFreeAssetNetUsage(0);
213 | contract.setFreeAssetNetLimit(0);
214 | contract.setPublicFreeAssetNetLimit(0);
215 |
216 | if (options.frozenSupply) {
217 | for (let frozenSupply of options.frozenSupply) {
218 | let frozenSupplyContract = new AssetIssueContract.FrozenSupply();
219 | frozenSupplyContract.setFrozenAmount(frozenSupply.amount);
220 | frozenSupplyContract.setFrozenDays(frozenSupply.days);
221 | contract.addFrozenSupply(frozenSupplyContract);
222 | }
223 | }
224 |
225 | return buildTransferContract(
226 | contract,
227 | Transaction.Contract.ContractType.ASSETISSUECONTRACT,
228 | "AssetIssueContract");
229 | }
230 |
231 | /**
232 | * Freeze balance
233 | *
234 | * @param address From which address to freze
235 | * @param amount The amount of TRX to freeze
236 | * @param duration Duration in days
237 | * @param andwith or energy Bandwidth Point = 0,Energy = 1
238 | */
239 | function buildFreezeBalance(address, amount, duration, resource, receiver) {
240 | let contract = new FreezeBalanceContract();
241 |
242 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
243 | contract.setFrozenBalance(amount);
244 | contract.setFrozenDuration(duration);
245 | contract.setResource(resource);
246 | if (receiver) {
247 | contract.setReceiverAddress(Uint8Array.from(decode58Check(receiver)));
248 | }
249 | return buildTransferContract(
250 | contract,
251 | Transaction.Contract.ContractType.FREEZEBALANCECONTRACT,
252 | "FreezeBalanceContract");
253 | }
254 |
255 | /**
256 | * Unfreeze balance
257 | *
258 | * @param address From which address to freeze
259 | */
260 | function buildUnfreezeBalance(address, resource, receiver) {
261 | let contract = new UnfreezeBalanceContract();
262 |
263 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
264 | contract.setResource(resource);
265 | if (receiver) {
266 | contract.setReceiverAddress(Uint8Array.from(decode58Check(receiver)));
267 | }
268 | return buildTransferContract(
269 | contract,
270 | Transaction.Contract.ContractType.UNFREEZEBALANCECONTRACT,
271 | "UnfreezeBalanceContract");
272 | }
273 |
274 | /**
275 | * Unfreeze Assets
276 | *
277 | * @param address From which address to unfreeze
278 | */
279 | function buildUnfreezeAsset(address) {
280 | let contract = new UnfreezeAssetContract();
281 |
282 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
283 |
284 | return buildTransferContract(
285 | contract,
286 | Transaction.Contract.ContractType.UNFREEZEASSETCONTRACT,
287 | "UnfreezeAssetContract");
288 | }
289 |
290 | /**
291 | * Create Exchange
292 | *
293 | * @param address From which address to create exchange
294 | * @param firstTokenID The first token id
295 | * @param secondTokenId The second token id
296 | * @param firstTokenBalance The balance of the first token
297 | * @param secondTokenBalance The balance of the second token
298 | */
299 | function buildExchangeCreate(address, firstTokenID, secondTokenId, firstTokenBalance, secondTokenBalance) {
300 | let contract = new ExchangeCreateContract();
301 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
302 | contract.setFirstTokenId(encodeString(firstTokenID));
303 | contract.setFirstTokenBalance(firstTokenBalance);
304 | contract.setSecondTokenId(encodeString(secondTokenId));
305 | contract.setSecondTokenBalance(secondTokenBalance);
306 |
307 | return buildTransferContract(
308 | contract,
309 | Transaction.Contract.ContractType.EXCHANGECREATECONTRACT,
310 | "ExchangeCreateContract");
311 | }
312 |
313 | /**
314 | * Inject Exchange
315 | *
316 | * @param address From which address to create exchange
317 | * @param exchangeId The id of the transaction pair
318 | * @param tokenId The id of the token to be funded
319 | * @param quant The amount of the token to be injected
320 | */
321 | function buildExchangeInject(address, exchangeId, tokenId, quant) {
322 | let contract = new ExchangeInjectContract();
323 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
324 | contract.setExchangeId(exchangeId);
325 | contract.setTokenId(encodeString(tokenId));
326 | contract.setQuant(quant);
327 |
328 | return buildTransferContract(
329 | contract,
330 | Transaction.Contract.ContractType.EXCHANGEINJECTCONTRACT,
331 | "ExchangeInjectContract");
332 | }
333 |
334 | /**
335 | * Withdraw Exchange
336 | *
337 | * @param address From which address to create exchange
338 | * @param exchangeId The id of the transaction pair
339 | * @param tokenId The id of the token to be funded
340 | * @param quant The amount of the token to be injected
341 | */
342 | function buildExchangeWithdraw(address, exchangeId, tokenId, quant) {
343 | let contract = new ExchangeWithdrawContract();
344 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
345 | contract.setExchangeId(exchangeId);
346 | contract.setTokenId(encodeString(tokenId));
347 | contract.setQuant(quant);
348 |
349 | return buildTransferContract(
350 | contract,
351 | Transaction.Contract.ContractType.EXCHANGEWITHDRAWCONTRACT,
352 | "ExchangeWithdrawContract");
353 | }
354 |
355 |
356 | /**
357 | * Withdraw Exchange
358 | *
359 | * @param address From which address to create exchange
360 | * @param exchangeId The id of the transaction pair
361 | * @param tokenId The id of the token to be funded
362 | * @param quant The amount of the token to be injected
363 | * @param expected The minimum amount of another token expected to be obtained. If it is less than this value, the transaction will not succeed
364 | */
365 | function buildTransactionExchange(address, exchange_id, token_id, quant, expected) {
366 | let contract = new ExchangeTransactionContract();
367 | contract.setOwnerAddress(Uint8Array.from(decode58Check(address)));
368 | contract.setExchangeId(exchange_id);
369 | contract.setTokenId(encodeString(token_id));
370 | contract.setQuant(quant);
371 | contract.setExpected(expected)
372 |
373 | return buildTransferContract(
374 | contract,
375 | Transaction.Contract.ContractType.EXCHANGETRANSACTIONCONTRACT,
376 | "ExchangeTransactionContract");
377 | }
378 |
379 | /**
380 | * Trigger Smart Contract
381 | *
382 | * @param value transaction parameter value
383 | */
384 | function buildTriggerSmartContract(value) {
385 | let contract = new TriggerSmartContract();
386 |
387 | contract.setOwnerAddress(fromHexString(value.owner_address));
388 | contract.setContractAddress(fromHexString(value.contract_address));
389 | contract.setData(fromHexString(value.data));
390 | if(value.token_id){
391 | contract.setTokenId(value.token_id);
392 | }
393 | if(value.call_token_value){
394 | contract.setCallTokenValue(value.call_token_value)
395 | }
396 | if(value.call_value){
397 | contract.setCallValue(value.call_value);
398 | }
399 | return parameterValue2hexStr(
400 | contract,
401 | Transaction.Contract.ContractType.TRIGGERSMARTCONTRACT,
402 | "TriggerSmartContract");
403 | }
404 |
405 | /**
406 | * Account Permission Update Contract
407 | *
408 | * @param value transaction parameter value
409 | */
410 |
411 | function buildAccountPermissionUpdateContract(value) {
412 | let contract = new AccountPermissionUpdateContract();
413 | const { owner, actives, witness, owner_address } = value;
414 | //contract.owner
415 | //set ownerAddress
416 | contract.setOwnerAddress(fromHexString(owner_address));
417 | //set owner
418 | const { keys, permission_name, threshold } = owner;
419 | {
420 | const permissionType = proto.protocol.Permission.PermissionType.OWNER;
421 | let ownerPermission = new proto.protocol.Permission();
422 |
423 | keys.forEach((item) => {
424 | let key = new proto.protocol.Key();
425 | key.setAddress(fromHexString(item.address));
426 | key.setWeight(item.weight);
427 | ownerPermission.addKeys(key)
428 | })
429 | ownerPermission.setPermissionName(permission_name);
430 | ownerPermission.setThreshold(threshold)
431 | contract.setOwner(ownerPermission);
432 | }
433 | {
434 | if (witness) {
435 | const { keys, permission_name, threshold,id } = witness;
436 | let witnessPermission = new proto.protocol.Permission();
437 | const permissionType = proto.protocol.Permission.PermissionType.WITNESS;
438 | keys.forEach((item) => {
439 | let key = new proto.protocol.Key();
440 | key.setAddress(fromHexString(item.address));
441 | key.setWeight(item.weight);
442 | witnessPermission.addKeys(key)
443 | })
444 | witnessPermission.setId(id);
445 | witnessPermission.setPermissionName(permission_name);
446 | witnessPermission.setThreshold(threshold);
447 | witnessPermission.setType(permissionType);
448 | contract.setWitness(witnessPermission);
449 | }
450 | }
451 |
452 |
453 | // active
454 | {
455 | const permissionType = proto.protocol.Permission.PermissionType.ACTIVE;
456 |
457 | actives.forEach((active) => {
458 | let activePermission = new proto.protocol.Permission();
459 | activePermission.setThreshold(active.threshold)
460 | activePermission.setType(permissionType)
461 | activePermission.setPermissionName(active.permission_name)
462 | activePermission.setOperations(fromHexString(active.operations));
463 | activePermission.setId(active.id);
464 | active.keys.forEach((item) => {
465 | let key = new proto.protocol.Key();
466 | key.setAddress(fromHexString(item.address));
467 | key.setWeight(item.weight);
468 | activePermission.addKeys(key);
469 | })
470 | contract.addActives(activePermission);
471 | })
472 | }
473 | return parameterValue2hexStr(
474 | contract,
475 | Transaction.Contract.ContractType.ACCOUNTPERMISSIONUPDATECONTRACT,
476 | "AccountPermissionUpdateContract");
477 | }
478 |
479 |
480 | /**
481 | * Trigger Smart Contract Parameter Value
482 | *
483 | * @param bytes type bytes parameter value
484 | */
485 | function getTriggerSmartContractParameterValue(bytes) {
486 | let contract = new TriggerSmartContract();
487 | let transaction = proto.protocol.TriggerSmartContract.deserializeBinary(bytes);
488 | let contract_address = byteArray2hexStr(transaction.getContractAddress());
489 | let data = byteArray2hexStr(transaction.getData());
490 | let owner_address = byteArray2hexStr(transaction.getOwnerAddress());
491 | let call_value = byteArray2hexStr(transaction.getCallValue());
492 | let parameterValue = {
493 | contract_address,
494 | data,
495 | call_value,
496 | owner_address
497 | }
498 | return parameterValue
499 | }
500 |
501 | /**
502 | * Transfer Contract Parameter Value
503 | *
504 | * @param bytes type bytes parameter value
505 | */
506 | function getTransferContractParameterValue(bytes) {
507 | let transferContract = new TransferContract();
508 | let transaction = proto.protocol.TransferContract.deserializeBinary(bytes);
509 | let owner_address = byteArray2hexStr(transaction.getOwnerAddress());
510 | let to_address = byteArray2hexStr(transaction.getToAddress());
511 | let amount = transaction.getAmount();
512 | let parameterValue = {
513 | owner_address,
514 | to_address,
515 | amount,
516 | }
517 | return parameterValue
518 | }
519 |
520 | /**
521 | * Transfer Asset Contract Parameter Value
522 | *
523 | * @param bytes type bytes parameter value
524 | */
525 | function getTransferAssetContractParameterValue(bytes) {
526 | let transferContract = new TransferAssetContract();
527 | let transaction = proto.protocol.TransferAssetContract.deserializeBinary(bytes);
528 | let asset_name = byteArray2hexStr(transaction.getAssetName());
529 | let to_address = byteArray2hexStr(transaction.getToAddress());
530 | let amount = transaction.getAmount();
531 | let owner_address = byteArray2hexStr(transaction.getOwnerAddress());
532 | let parameterValue = {
533 | owner_address,
534 | to_address,
535 | amount,
536 | asset_name
537 | }
538 | return parameterValue
539 | }
540 |
541 | /**
542 | * Account Permission Update Contract Parameter Value
543 | *
544 | * @param bytes type bytes parameter value
545 | */
546 | function getAccountPermissionUpdateContractParameterValue(bytes) {
547 | let accountPermissionUpdateContract = new AccountPermissionUpdateContract();
548 | let transaction = proto.protocol.AccountPermissionUpdateContract.deserializeBinary(bytes);
549 |
550 | let owner_address = byteArray2hexStr(transaction.getOwnerAddress());
551 |
552 | //get owner
553 | const permissionType = proto.protocol.Permission.PermissionType.OWNER;
554 | let ownerPermission = transaction.getOwner();
555 | let ownerKeys = ownerPermission.getKeysList();
556 | let ownerKeysArr = [];
557 | ownerKeys.forEach((key) => {
558 | ownerKeysArr.push({
559 | 'address':byteArray2hexStr(key.getAddress()),
560 | 'weight':key.getWeight()
561 | })
562 | })
563 | let ownerThreshold = ownerPermission.getThreshold()
564 | let ownerPermissionName = ownerPermission.getPermissionName();
565 | let owner = {
566 | "keys":ownerKeysArr,
567 | "threshold":ownerThreshold,
568 | "permission_name":ownerPermissionName
569 | }
570 | let witness =''
571 | if (transaction.getWitness()) {
572 | let witnessPermission = transaction.getWitness();
573 | let witnessKeys = witnessPermission.getKeysList();
574 | let witnessKeysArr = [];
575 | witnessKeys.forEach((key) => {
576 | ownerKeysArr.push({
577 | 'address':byteArray2hexStr(key.getAddress()),
578 | 'weight':key.getWeight()
579 | })
580 | })
581 | let witnessId = witnessPermission.getId();
582 | let witnessThreshold = witnessPermission.getThreshold();
583 | let witnessPermissionName = witnessPermission.getPermissionName();
584 | let witnessType = witnessPermission.getType();
585 | witness = {
586 | "keys":witnessKeysArr,
587 | "id":witnessId,
588 | "threshold":witnessThreshold,
589 | "permission_name":witnessPermissionName,
590 | "type":witnessType
591 | }
592 | }
593 | // active
594 | let activesPermission = transaction.getActivesList();
595 | let actives = [];
596 | activesPermission.forEach((active) => {
597 | let activeKeys = active.getKeysList();
598 | let activeKeysArr = [];
599 | activeKeys.forEach((key) => {
600 | activeKeysArr.push({
601 | 'address':byteArray2hexStr(key.getAddress()),
602 | 'weight':key.getWeight()
603 | })
604 | })
605 | actives.push(
606 | {
607 | "operations": byteArray2hexStr(active.getOperations()),
608 | "keys": activeKeysArr,
609 | "threshold":active.getThreshold(),
610 | "id":active.getId(),
611 | "type":active.getType(),
612 | "permission_name":active.getPermissionName()
613 | }
614 | )
615 | })
616 |
617 | let parameterValue = {
618 | owner,
619 | actives,
620 | witness:transaction.getWitness()?witness:'',
621 | owner_address
622 | }
623 | return parameterValue
624 | }
625 |
626 |
627 |
628 |
629 | module.exports = {
630 | buildTransferTransaction,
631 | buildAccountUpdate,
632 | buildAssetParticipate,
633 | buildVote,
634 | buildFreezeBalance,
635 | buildUnfreezeBalance,
636 | buildAssetIssue,
637 | buildWitnessUpdate,
638 | buildWithdrawBalance,
639 | buildWitnessCreate,
640 | buildUnfreezeAsset,
641 | buildExchangeCreate,
642 | buildExchangeInject,
643 | buildExchangeWithdraw,
644 | buildTransactionExchange,
645 | buildTransferContract,
646 | buildAssetUpdate,
647 | buildTransferHexStr,
648 | buildTriggerSmartContract,
649 | buildAccountPermissionUpdateContract,
650 | getTriggerSmartContractParameterValue,
651 | getTransferContractParameterValue,
652 | getTransferAssetContractParameterValue,
653 | getAccountPermissionUpdateContractParameterValue,
654 | };
655 |
656 |
--------------------------------------------------------------------------------
/src/utils/tronWeb.js:
--------------------------------------------------------------------------------
1 | const { buildTransferContract } = require("./transactionBuilder");
2 | const { Block, Transaction, Account } = require("../protocol/core/Tron_pb");
3 |
4 | const {
5 | TransferContract,
6 | TransferAssetContract,
7 | AccountUpdateContract,
8 | VoteWitnessContract,
9 | ParticipateAssetIssueContract,
10 | AssetIssueContract,
11 | FreezeBalanceContract,
12 | UnfreezeBalanceContract,
13 | WitnessUpdateContract,
14 | WithdrawBalanceContract,
15 | WitnessCreateContract,
16 | UnfreezeAssetContract,
17 | TriggerSmartContract,
18 | ExchangeTransactionContract,
19 | ExchangeCreateContract,
20 | ExchangeWithdrawContract,
21 | ExchangeInjectContract,
22 | AccountPermissionUpdateContract,
23 | } = require("../protocol/core/Contract_pb");
24 |
25 | const fromHexString = hexString =>
26 | new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
27 |
28 | export function transactionJsonToProtoBuf(transaction) {
29 | const rawData = transaction["raw_data"];
30 | const contractJson = rawData.contract[0];
31 | const transactionObj = contractJsonToProtobuf(contractJson);
32 | // if(contractJson.Permission_id){
33 | // transactionObj.setPermissionId(contractJson.Permission_id);
34 | // }
35 | const rawDataObj = transactionObj.getRawData();
36 | rawDataObj.setRefBlockBytes(fromHexString(rawData.ref_block_bytes));
37 | rawDataObj.setRefBlockHash(fromHexString(rawData.ref_block_hash));
38 | if (rawData.expiration) {
39 | rawDataObj.setExpiration(rawData.expiration);
40 | }
41 | if (rawData.data) {
42 | rawDataObj.setData(fromHexString(rawData.data));
43 | }
44 | if (rawData.timestamp) {
45 | rawDataObj.setTimestamp(rawData.timestamp);
46 | }
47 | if (rawData.fee_limit) {
48 | rawDataObj.setFeeLimit(rawData.fee_limit);
49 | }
50 | // contractObj.setPermission
51 | transactionObj.setRawData(rawDataObj);
52 | return transactionObj;
53 | }
54 |
55 | export function contractJsonToProtobuf(contract) {
56 | const value = contract.parameter.value;
57 | switch (contract.type) {
58 |
59 | case "TransferContract": {
60 | const { to_address, owner_address, amount } = value;
61 | let transferContract = new TransferContract();
62 | transferContract.setToAddress(fromHexString(to_address));
63 | transferContract.setOwnerAddress(fromHexString(owner_address));
64 | transferContract.setAmount(amount);
65 | return buildTransferContract(
66 | transferContract,
67 | Transaction.Contract.ContractType.TRANSFERCONTRACT,
68 | "TransferContract",contract.Permission_id);
69 | }
70 |
71 | case "TransferAssetContract": {
72 | const { to_address, owner_address, amount, asset_name } = value;
73 | let transferContract = new TransferAssetContract();
74 | transferContract.setToAddress(fromHexString(to_address));
75 | transferContract.setOwnerAddress(fromHexString(owner_address));
76 | transferContract.setAssetName(fromHexString(asset_name));
77 | transferContract.setAmount(amount);
78 | return buildTransferContract(
79 | transferContract,
80 | Transaction.Contract.ContractType.TRANSFERASSETCONTRACT,
81 | "TransferAssetContract",contract.Permission_id);
82 | }
83 |
84 | case "AccountUpdateContract": {
85 | const { owner_address, account_name } = value;
86 | let contract = new AccountUpdateContract();
87 | contract.setOwnerAddress(fromHexString(owner_address));
88 | contract.setAccountName(fromHexString(account_name));
89 |
90 | return buildTransferContract(
91 | contract,
92 | Transaction.Contract.ContractType.ACCOUNTUPDATECONTRACT,
93 | "AccountUpdateContract");
94 | }
95 |
96 | case "WitnessCreateContract": {
97 |
98 | let contract = new WitnessCreateContract();
99 | contract.setOwnerAddress(fromHexString(value.owner_address));
100 | contract.setUrl(value.url);
101 |
102 | return buildTransferContract(
103 | contract,
104 | Transaction.Contract.ContractType.WITNESSCREATECONTRACT,
105 | "WitnessCreateContract");
106 | }
107 |
108 |
109 | case "WitnessUpdateContract": {
110 |
111 | let contract = new WitnessUpdateContract();
112 | contract.setOwnerAddress(fromHexString(value.owner_address));
113 | contract.setUpdateUrl(value.url);
114 |
115 | return buildTransferContract(
116 | contract,
117 | Transaction.Contract.ContractType.WITNESSUPDATECONTRACT,
118 | "WitnessUpdateContract");
119 | }
120 |
121 | case "WithdrawBalanceContract": {
122 |
123 | let contract = new WithdrawBalanceContract();
124 | contract.setOwnerAddress(fromHexString(value.owner_address));
125 |
126 | return buildTransferContract(
127 | contract,
128 | Transaction.Contract.ContractType.WITHDRAWBALANCECONTRACT,
129 | "WithdrawBalanceContract");
130 | }
131 |
132 | case "FreezeBalanceContract": {
133 |
134 | // TODO ADD ENERGY SWITCH
135 |
136 | let contract = new FreezeBalanceContract();
137 |
138 | contract.setOwnerAddress(fromHexString(value.owner_address));
139 | contract.setFrozenBalance(value.frozen_balance);
140 | contract.setFrozenDuration(value.frozen_duration);
141 | if (value.resource === 'ENERGY') {
142 | contract.setResource(1);
143 | }
144 | else {
145 | contract.setResource(0);
146 | }
147 |
148 |
149 | if (value.receiver_address) {
150 | contract.setReceiverAddress(fromHexString(value.receiver_address));
151 | }
152 |
153 | return buildTransferContract(
154 | contract,
155 | Transaction.Contract.ContractType.FREEZEBALANCECONTRACT,
156 | "FreezeBalanceContract");
157 | }
158 |
159 |
160 | case "VoteWitnessContract": {
161 | let contract = new VoteWitnessContract();
162 | contract.setOwnerAddress(fromHexString(value.owner_address));
163 |
164 | for (let address of value.votes) {
165 | let vote = new VoteWitnessContract.Vote();
166 | vote.setVoteAddress(fromHexString(address.vote_address));
167 | vote.setVoteCount(address.vote_count);
168 | contract.addVotes(vote);
169 | }
170 |
171 | return buildTransferContract(
172 | contract,
173 | Transaction.Contract.ContractType.VOTEWITNESSCONTRACT,
174 | "VoteWitnessContract");
175 | }
176 |
177 | case "ParticipateAssetIssueContract": {
178 |
179 | let contract = new ParticipateAssetIssueContract();
180 | contract.setToAddress(fromHexString(value.to_address));
181 | contract.setOwnerAddress(fromHexString(value.owner_address));
182 | contract.setAssetName(fromHexString(value.asset_name));
183 | contract.setAmount(value.amount);
184 |
185 | return buildTransferContract(
186 | contract,
187 | Transaction.Contract.ContractType.PARTICIPATEASSETISSUECONTRACT,
188 | "ParticipateAssetIssueContract");
189 | }
190 |
191 | case "UnfreezeBalanceContract": {
192 |
193 | // TODO ADD ENERGY SWITCH
194 |
195 | let contract = new UnfreezeBalanceContract();
196 |
197 | contract.setOwnerAddress(fromHexString(value.owner_address));
198 | if (value.resource === 'ENERGY') {
199 | contract.setResource(1);
200 | }
201 | else {
202 | contract.setResource(0);
203 | }
204 |
205 | if (value.receiver_address) {
206 | contract.setReceiverAddress(fromHexString(value.receiver_address));
207 | }
208 | return buildTransferContract(
209 | contract,
210 | Transaction.Contract.ContractType.UNFREEZEBALANCECONTRACT,
211 | "UnfreezeBalanceContract");
212 | }
213 |
214 | case "UnfreezeAssetContract": {
215 |
216 | let contract = new UnfreezeAssetContract();
217 |
218 | contract.setOwnerAddress(fromHexString(value.owner_address));
219 |
220 | return buildTransferContract(
221 | contract,
222 | Transaction.Contract.ContractType.UNFREEZEASSETCONTRACT,
223 | "UnfreezeAssetContract");
224 | }
225 |
226 | case "TriggerSmartContract": {
227 | let triggerSmartContract = new TriggerSmartContract();
228 | triggerSmartContract.setOwnerAddress(fromHexString(value.owner_address));
229 | triggerSmartContract.setContractAddress(fromHexString(value.contract_address));
230 | triggerSmartContract.setCallValue(value.call_value);
231 | triggerSmartContract.setData(fromHexString(value.data));
232 |
233 | return buildTransferContract(
234 | triggerSmartContract,
235 | Transaction.Contract.ContractType.TRIGGERSMARTCONTRACT,
236 | "TriggerSmartContract",contract.Permission_id);
237 | }
238 |
239 | case "ExchangeTransactionContract": {
240 | let contract = new ExchangeTransactionContract();
241 | contract.setOwnerAddress(fromHexString(value.owner_address));
242 | contract.setExchangeId(value.exchange_id);
243 | contract.setTokenId(fromHexString(value.token_id));
244 | contract.setQuant(value.quant);
245 | contract.setExpected(value.expected);
246 |
247 | return buildTransferContract(
248 | contract,
249 | Transaction.Contract.ContractType.EXCHANGETRANSACTIONCONTRACT,
250 | "ExchangeTransactionContract");
251 | }
252 |
253 | case "ExchangeCreateContract": {
254 |
255 | let contract = new ExchangeCreateContract();
256 |
257 | contract.setOwnerAddress(fromHexString(value.owner_address));
258 | contract.setFirstTokenId(fromHexString(value.first_token_id));
259 | contract.setFirstTokenBalance(value.first_token_balance);
260 | contract.setSecondTokenId(fromHexString(value.second_token_id));
261 | contract.setSecondTokenBalance(value.second_token_balance);
262 |
263 | return buildTransferContract(
264 | contract,
265 | Transaction.Contract.ContractType.EXCHANGECREATECONTRACT,
266 | "ExchangeCreateContract");
267 | }
268 |
269 | case "ExchangeInjectContract": {
270 |
271 | let contract = new ExchangeInjectContract();
272 |
273 | contract.setOwnerAddress(fromHexString(value.owner_address));
274 | contract.setExchangeId(value.exchange_id);
275 | contract.setTokenId(fromHexString(value.token_id));
276 | contract.setQuant(value.quant);
277 |
278 | return buildTransferContract(
279 | contract,
280 | Transaction.Contract.ContractType.EXCHANGEINJECTCONTRACT,
281 | "ExchangeInjectContract");
282 | }
283 |
284 | case "ExchangeWithdrawContract": {
285 |
286 | let contract = new ExchangeWithdrawContract();
287 |
288 | contract.setOwnerAddress(fromHexString(value.owner_address));
289 | contract.setExchangeId(value.exchange_id);
290 | contract.setTokenId(fromHexString(value.token_id));
291 | contract.setQuant(value.quant);
292 |
293 | return buildTransferContract(
294 | contract,
295 | Transaction.Contract.ContractType.EXCHANGEWITHDRAWCONTRACT,
296 | "ExchangeWithdrawContract");
297 | }
298 |
299 | case "AccountPermissionUpdateContract":{
300 | let accountPermissionUpdateContract = new AccountPermissionUpdateContract();
301 | const { owner, actives, witness, owner_address } = value;
302 | //set ownerAddress
303 | accountPermissionUpdateContract.setOwnerAddress(fromHexString(owner_address));
304 | //set owner
305 | const { keys, permission_name, threshold } = owner;
306 | {
307 | const permissionType = proto.protocol.Permission.PermissionType.OWNER;
308 | let ownerPermission = new proto.protocol.Permission();
309 |
310 | keys.forEach((item) => {
311 | let key = new proto.protocol.Key();
312 | key.setAddress(fromHexString(item.address));
313 | key.setWeight(item.weight);
314 | ownerPermission.addKeys(key)
315 | })
316 | ownerPermission.setPermissionName(permission_name);
317 | ownerPermission.setThreshold(threshold)
318 | accountPermissionUpdateContract.setOwner(ownerPermission);
319 | }
320 | {
321 | if (witness) {
322 | const { keys, permission_name, threshold,id } = witness;
323 | let witnessPermission = new proto.protocol.Permission();
324 | const permissionType = proto.protocol.Permission.PermissionType.WITNESS;
325 | keys.forEach((item) => {
326 | let key = new proto.protocol.Key();
327 | key.setAddress(fromHexString(item.address));
328 | key.setWeight(item.weight);
329 | witnessPermission.addKeys(key)
330 | })
331 | witnessPermission.setId(id);
332 | witnessPermission.setPermissionName(permission_name);
333 | witnessPermission.setThreshold(threshold);
334 | witnessPermission.setType(permissionType);
335 | accountPermissionUpdateContract.setWitness(witnessPermission);
336 | }
337 | }
338 |
339 |
340 | // active
341 | {
342 | const permissionType = proto.protocol.Permission.PermissionType.ACTIVE;
343 |
344 | actives.forEach((active) => {
345 | let activePermission = new proto.protocol.Permission();
346 | activePermission.setThreshold(active.threshold)
347 | activePermission.setType(permissionType)
348 | activePermission.setPermissionName(active.permission_name)
349 | activePermission.setOperations(fromHexString(active.operations));
350 | activePermission.setId(active.id);
351 | active.keys.forEach((item) => {
352 | let key = new proto.protocol.Key();
353 | key.setAddress(fromHexString(item.address));
354 | key.setWeight(item.weight);
355 | activePermission.addKeys(key);
356 | })
357 | accountPermissionUpdateContract.addActives(activePermission);
358 | })
359 | }
360 | return buildTransferContract(
361 | accountPermissionUpdateContract,
362 | Transaction.Contract.ContractType.ACCOUNTPERMISSIONUPDATECONTRACT,
363 | "AccountPermissionUpdateContract",contract.Permission_id);
364 | }
365 |
366 | }
367 | }
368 |
--------------------------------------------------------------------------------
/test/transactionBuilder.js:
--------------------------------------------------------------------------------
1 | const buildWithdrawBalance = require("../src/utils/transactionBuilder").buildWithdrawBalance;
2 | const buildUnfreezeBalance = require("../src/utils/transactionBuilder").buildUnfreezeBalance;
3 | const buildFreezeBalance = require("../src/utils/transactionBuilder").buildFreezeBalance;
4 | const byteArray2hexStr = require("../src/utils/bytes").byteArray2hexStr;
5 | const buildVote = require("../src/utils/transactionBuilder").buildVote;
6 | const { assert } = require('chai');
7 |
8 | describe('transactionBuilder', () => {
9 |
10 | it('build voteContract', async () => {
11 | let transaction = buildVote("TKcrAJN3tgLshGqp7aTDTJLabdWqZSKFMx", {
12 | "TKcrAJN3tgLshGqp7aTDTJLabdWqZSKFMx": 100
13 | });
14 |
15 | console.log("hex", byteArray2hexStr(transaction.getRawData().serializeBinary()));
16 | });
17 |
18 | it('build freeze', async () => {
19 | let transaction = buildFreezeBalance("TKcrAJN3tgLshGqp7aTDTJLabdWqZSKFMx", 100000000, 3);
20 | console.log("hex", byteArray2hexStr(transaction.getRawData().serializeBinary()));
21 | });
22 |
23 | it('build unfreeze', async () => {
24 | let transaction = buildUnfreezeBalance("TKcrAJN3tgLshGqp7aTDTJLabdWqZSKFMx");
25 | console.log("hex", byteArray2hexStr(transaction.getRawData().serializeBinary()));
26 | });
27 |
28 | it('build withdraw', async () => {
29 | let transaction = buildWithdrawBalance("TKcrAJN3tgLshGqp7aTDTJLabdWqZSKFMx");
30 | console.log("hex", byteArray2hexStr(transaction.getRawData().serializeBinary()));
31 | });
32 |
33 | });
34 |
--------------------------------------------------------------------------------