This commit is contained in:
nitowa
2023-08-15 22:28:03 +02:00
commit 1dae68b1c7
5529 changed files with 1659171 additions and 0 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Ripple Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+196
View File
@@ -0,0 +1,196 @@
# ripple-address-codec
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Functions for encoding and decoding XRP Ledger addresses and seeds.
Also includes support for encoding/decoding [rippled validator (node) public keys](https://xrpl.org/run-rippled-as-a-validator.html).
[![NPM](https://nodei.co/npm/ripple-address-codec.png)](https://www.npmjs.org/package/ripple-address-codec)
## X-address Conversion
All tools and apps in the XRP Ledger ecosystem are encouraged to adopt support for the X-address format. The X-address format is a single Base58 string that encodes an 'Account ID', a (destination) tag, and whether the address is intended for a test network. This prevents users from unintentionally omitting the destination tag when sending and receiving payments and other transactions.
## API
### classicAddressToXAddress(classicAddress: string, tag: number | false, test: boolean): string
Convert a classic address and (optional) tag to an X-address. If `tag` is `false`, the returned X-address explicitly indicates that the recipient does not want a tag to be used. If `test` is `true`, consumers of the address will know that the address is intended for use on test network(s) and the address will start with `T`.
```js
> const api = require('ripple-address-codec')
> api.classicAddressToXAddress('rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 4294967295)
'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi'
```
Encode a test address e.g. for use with [Testnet or Devnet](https://xrpl.org/xrp-testnet-faucet.html):
```js
> const api = require('ripple-address-codec')
> api.classicAddressToXAddress('r3SVzk8ApofDJuVBPKdmbbLjWGCCXpBQ2g', 123, true)
'T7oKJ3q7s94kDH6tpkBowhetT1JKfcfdSCmAXbS75iATyLD'
```
### xAddressToClassicAddress(xAddress: string): {classicAddress: string, tag: number | false, test: boolean}
Convert an X-address to a classic address and tag. If the X-address did not have a tag, the returned object's `tag` will be `false`. (Since `0` is a valid tag, instead of `if (tag)`, use `if (tag !== false)` if you want to check for a tag.) If the X-address is intended for use on test network(s), `test` will be `true`; if it is intended for use on the main network (mainnet), `test` will be `false`.
```js
> const api = require('ripple-address-codec')
> api.xAddressToClassicAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi')
{
classicAddress: 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf',
tag: 4294967295,
test: false
}
```
### isValidXAddress(xAddress: string): boolean
Returns `true` if the provided X-address is valid, or `false` otherwise.
```js
> const api = require('ripple-address-codec')
> api.isValidXAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi')
true
```
Returns `false` for classic addresses (starting with `r`). To validate a classic address, use `isValidClassicAddress`.
### isValidClassicAddress(address: string): boolean
Check whether a classic address (starting with `r`...) is valid.
Returns `false` for X-addresses (extended addresses). To validate an X-address, use `isValidXAddress`.
### encodeSeed(entropy: Buffer, type: 'ed25519' | 'secp256k1'): string
Encode the given entropy as an XRP Ledger seed (secret). The entropy must be exactly 16 bytes (128 bits). The encoding includes which elliptic curve digital signature algorithm (ECDSA) the seed is intended to be used with. The seed is used to produce the private key.
### decodeSeed(seed: string): object
Decode a seed into an object with its version, type, and bytes.
Return object type:
```
{
version: number[],
bytes: Buffer,
type: string | null
}
```
### encodeAccountID(bytes: Buffer): string
Encode bytes as a classic address (starting with `r`...).
### decodeAccountID(accountId: string): Buffer
Decode a classic address (starting with `r`...) to its raw bytes.
### encodeNodePublic(bytes: Buffer): string
Encode bytes to the XRP Ledger "node public key" format (base58).
This is useful for rippled validators.
### decodeNodePublic(base58string: string): Buffer
Decode an XRP Ledger "node public key" (in base58 format) into its raw bytes.
### encodeAccountPublic(bytes: Buffer): string
Encode a public key, as for payment channels.
### decodeAccountPublic(base58string: string): Buffer
Decode a public key, as for payment channels.
### encodeXAddress(accountId: Buffer, tag: number | false, test: boolean): string
Encode account ID, tag, and network ID to X-address.
`accountId` must be 20 bytes because it is a RIPEMD160 hash, which is 160 bits (160 bits = 20 bytes).
At this time, `tag` must be <= MAX_32_BIT_UNSIGNED_INT (4294967295) as the XRP Ledger only supports 32-bit tags.
If `test` is `true`, this address is intended for use with a test network such as Testnet or Devnet.
### decodeXAddress(xAddress: string): {accountId: Buffer, tag: number | false, test: boolean}
Convert an X-address to its classic address, tag, and network ID.
### Other functions
```js
> var api = require('ripple-address-codec');
> api.decodeSeed('sEdTM1uX8pu2do5XvTnutH6HsouMaM2')
{ version: [ 1, 225, 75 ],
bytes: [ 76, 58, 29, 33, 63, 189, 251, 20, 199, 194, 141, 96, 148, 105, 179, 65 ],
type: 'ed25519' }
> api.decodeSeed('sn259rEFXrQrWyx3Q7XneWcwV6dfL')
{ version: 33,
bytes: [ 207, 45, 227, 120, 251, 221, 126, 46, 232, 125, 72, 109, 251, 90, 123, 255 ],
type: 'secp256k1' }
> api.decodeAccountID('rJrRMgiRgrU6hDF4pgu5DXQdWyPbY35ErN')
[ 186,
142,
120,
98,
110,
228,
44,
65,
180,
109,
70,
195,
4,
141,
243,
161,
195,
200,
112,
114 ]
```
## Tests
Run unit tests with:
npm test
Use `--watch` to run in watch mode, so that when you modify the tests, they are automatically re-run:
npm test -- --watch
Use `--coverage` to generate and display code coverage information:
npm test -- --coverage
This tells jest to output code coverage info in the `./coverage` directory, in addition to showing it on the command line.
## Releases
Use the [xrpl.js release process](https://github.com/XRPLF/xrpl.js/blob/main/CONTRIBUTING.md#release).
## Acknowledgements
This library references and adopts code and standards from the following sources:
- [XLS-5d Standard for Tagged Addresses](https://github.com/xrp-community/standards-drafts/issues/6) by @nbougalis
- [XRPL Tagged Address Codec](https://github.com/xrp-community/xrpl-tagged-address-codec) by @WietseWind
- [X-Address transaction functions](https://github.com/codetsunami/xrpl-tools/tree/master/xaddress-functions) by @codetsunami
[coveralls-image]: https://badgen.net/coveralls/c/github/ripple/ripple-address-codec/master
[coveralls-url]: https://coveralls.io/r/ripple/ripple-address/codec?branch=master
[npm-downloads-image]: https://badgen.net/npm/dm/ripple-address-codec
[npm-url]: https://npmjs.org/package/ripple-address-codec
[npm-version-image]: https://badgen.net/npm/v/ripple-address-codec
[travis-image]: https://badgen.net/travis/ripple/ripple-address-codec/master
[travis-url]: https://travis-ci.org/github/ripple/ripple-address-codec
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="node" />
import { codec, encodeSeed, decodeSeed, encodeAccountID, decodeAccountID, encodeNodePublic, decodeNodePublic, encodeAccountPublic, decodeAccountPublic, isValidClassicAddress } from './xrp-codec';
declare function classicAddressToXAddress(classicAddress: string, tag: number | false, test: boolean): string;
declare function encodeXAddress(accountId: Buffer, tag: number | false, test: boolean): string;
declare function xAddressToClassicAddress(xAddress: string): {
classicAddress: string;
tag: number | false;
test: boolean;
};
declare function decodeXAddress(xAddress: string): {
accountId: Buffer;
tag: number | false;
test: boolean;
};
declare function isValidXAddress(xAddress: string): boolean;
export { codec, encodeSeed, decodeSeed, encodeAccountID, decodeAccountID, encodeNodePublic, decodeNodePublic, encodeAccountPublic, decodeAccountPublic, isValidClassicAddress, classicAddressToXAddress, encodeXAddress, xAddressToClassicAddress, decodeXAddress, isValidXAddress, };
+153
View File
@@ -0,0 +1,153 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidXAddress = exports.decodeXAddress = exports.xAddressToClassicAddress = exports.encodeXAddress = exports.classicAddressToXAddress = exports.isValidClassicAddress = exports.decodeAccountPublic = exports.encodeAccountPublic = exports.decodeNodePublic = exports.encodeNodePublic = exports.decodeAccountID = exports.encodeAccountID = exports.decodeSeed = exports.encodeSeed = exports.codec = void 0;
const assert = __importStar(require("assert"));
const xrp_codec_1 = require("./xrp-codec");
Object.defineProperty(exports, "codec", { enumerable: true, get: function () { return xrp_codec_1.codec; } });
Object.defineProperty(exports, "encodeSeed", { enumerable: true, get: function () { return xrp_codec_1.encodeSeed; } });
Object.defineProperty(exports, "decodeSeed", { enumerable: true, get: function () { return xrp_codec_1.decodeSeed; } });
Object.defineProperty(exports, "encodeAccountID", { enumerable: true, get: function () { return xrp_codec_1.encodeAccountID; } });
Object.defineProperty(exports, "decodeAccountID", { enumerable: true, get: function () { return xrp_codec_1.decodeAccountID; } });
Object.defineProperty(exports, "encodeNodePublic", { enumerable: true, get: function () { return xrp_codec_1.encodeNodePublic; } });
Object.defineProperty(exports, "decodeNodePublic", { enumerable: true, get: function () { return xrp_codec_1.decodeNodePublic; } });
Object.defineProperty(exports, "encodeAccountPublic", { enumerable: true, get: function () { return xrp_codec_1.encodeAccountPublic; } });
Object.defineProperty(exports, "decodeAccountPublic", { enumerable: true, get: function () { return xrp_codec_1.decodeAccountPublic; } });
Object.defineProperty(exports, "isValidClassicAddress", { enumerable: true, get: function () { return xrp_codec_1.isValidClassicAddress; } });
const PREFIX_BYTES = {
// 5, 68
main: Buffer.from([0x05, 0x44]),
// 4, 147
test: Buffer.from([0x04, 0x93]),
};
const MAX_32_BIT_UNSIGNED_INT = 4294967295;
function classicAddressToXAddress(classicAddress, tag, test) {
const accountId = (0, xrp_codec_1.decodeAccountID)(classicAddress);
return encodeXAddress(accountId, tag, test);
}
exports.classicAddressToXAddress = classicAddressToXAddress;
function encodeXAddress(accountId, tag, test) {
if (accountId.length !== 20) {
// RIPEMD160 is 160 bits = 20 bytes
throw new Error('Account ID must be 20 bytes');
}
if (tag > MAX_32_BIT_UNSIGNED_INT) {
throw new Error('Invalid tag');
}
const theTag = tag || 0;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Passing null is a common js mistake
const flag = tag === false || tag == null ? 0 : 1;
/* eslint-disable no-bitwise ---
* need to use bitwise operations here */
const bytes = Buffer.concat([
test ? PREFIX_BYTES.test : PREFIX_BYTES.main,
accountId,
Buffer.from([
// 0x00 if no tag, 0x01 if 32-bit tag
flag,
// first byte
theTag & 0xff,
// second byte
(theTag >> 8) & 0xff,
// third byte
(theTag >> 16) & 0xff,
// fourth byte
(theTag >> 24) & 0xff,
0,
0,
0,
// four zero bytes (reserved for 64-bit tags)
0,
]),
]);
/* eslint-enable no-bitwise */
return xrp_codec_1.codec.encodeChecked(bytes);
}
exports.encodeXAddress = encodeXAddress;
function xAddressToClassicAddress(xAddress) {
/* eslint-disable @typescript-eslint/naming-convention --
* TODO 'test' should be something like 'isTest', do this later
*/
const { accountId, tag, test } = decodeXAddress(xAddress);
/* eslint-enable @typescript-eslint/naming-convention */
const classicAddress = (0, xrp_codec_1.encodeAccountID)(accountId);
return {
classicAddress,
tag,
test,
};
}
exports.xAddressToClassicAddress = xAddressToClassicAddress;
function decodeXAddress(xAddress) {
const decoded = xrp_codec_1.codec.decodeChecked(xAddress);
/* eslint-disable @typescript-eslint/naming-convention --
* TODO 'test' should be something like 'isTest', do this later
*/
const test = isBufferForTestAddress(decoded);
/* eslint-enable @typescript-eslint/naming-convention */
const accountId = decoded.slice(2, 22);
const tag = tagFromBuffer(decoded);
return {
accountId,
tag,
test,
};
}
exports.decodeXAddress = decodeXAddress;
function isBufferForTestAddress(buf) {
const decodedPrefix = buf.slice(0, 2);
if (PREFIX_BYTES.main.equals(decodedPrefix)) {
return false;
}
if (PREFIX_BYTES.test.equals(decodedPrefix)) {
return true;
}
throw new Error('Invalid X-address: bad prefix');
}
function tagFromBuffer(buf) {
const flag = buf[22];
if (flag >= 2) {
// No support for 64-bit tags at this time
throw new Error('Unsupported X-address');
}
if (flag === 1) {
// Little-endian to big-endian
return buf[23] + buf[24] * 0x100 + buf[25] * 0x10000 + buf[26] * 0x1000000;
}
assert.strictEqual(flag, 0, 'flag must be zero to indicate no tag');
assert.ok(Buffer.from('0000000000000000', 'hex').equals(buf.slice(23, 23 + 8)), 'remaining bytes must be zero');
return false;
}
function isValidXAddress(xAddress) {
try {
decodeXAddress(xAddress);
}
catch (_error) {
return false;
}
return true;
}
exports.isValidXAddress = isValidXAddress;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAEhC,2CAWoB;AA6IlB,sFAvJA,iBAAK,OAuJA;AAEL,2FAxJA,sBAAU,OAwJA;AAEV,2FAzJA,sBAAU,OAyJA;AAEV,gGA1JA,2BAAe,OA0JA;AAEf,gGA3JA,2BAAe,OA2JA;AAEf,iGA5JA,4BAAgB,OA4JA;AAEhB,iGA7JA,4BAAgB,OA6JA;AAEhB,oGA9JA,+BAAmB,OA8JA;AAEnB,oGA/JA,+BAAmB,OA+JA;AAEnB,sGAhKA,iCAAqB,OAgKA;AA7JvB,MAAM,YAAY,GAAG;IACnB,QAAQ;IACR,IAAI,EAAE,MAAM,CAAC,IA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;KACZ;IAED,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;AAClD,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IAChC,MAAM,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC,CAAA;IACpB,IAAI,IAAI,IAAI,CAAC,EAAE;QACb,0CAA0C;QAC1C,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAA;KACzC;IACD,IAAI,IAAI,KAAK,CAAC,EAAE;QACd,8BAA8B;QAC9B,OAAO,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAA;KAC3E;IACD,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,EAAE,sCAAsC,CAAC,CAAA;IACnE,MAAM,CAAC,EAAE,CACP,MAAM,CAAC,IAAI,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EACpE,8BAA8B,CAC/B,CAAA;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,eAAe,CAAC,QAAgB;IACvC,IAAI;QACF,cAAc,CAAC,QAAQ,CAAC,CAAA;KACzB;IAAC,OAAO,MAAM,EAAE;QACf,OAAO,KAAK,CAAA;KACb;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAgCC,0CAAe"}
+22
View File
@@ -0,0 +1,22 @@
/// <reference types="node" />
type Sequence = number[] | Buffer | Uint8Array;
/**
* Check whether two sequences (e.g. Arrays of numbers) are equal.
*
* @param arr1 - One of the arrays to compare.
* @param arr2 - The other array to compare.
*/
export declare function seqEqual(arr1: Sequence, arr2: Sequence): boolean;
/**
* Concatenate all `arguments` into a single array. Each argument can be either
* a single element or a sequence, which has a `length` property and supports
* element retrieval via sequence[ix].
*
* > concatArgs(1, [2, 3], Buffer.from([4,5]), new Uint8Array([6, 7]));
* [1,2,3,4,5,6,7]
*
* @param args - Concatenate of these args into a single array.
* @returns Array of concatenated arguments
*/
export declare function concatArgs(...args: Array<number | Sequence>): number[];
export {};
+56
View File
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.concatArgs = exports.seqEqual = void 0;
/**
* Check whether two sequences (e.g. Arrays of numbers) are equal.
*
* @param arr1 - One of the arrays to compare.
* @param arr2 - The other array to compare.
*/
function seqEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
exports.seqEqual = seqEqual;
/**
* Check whether a value is a sequence (e.g. Array of numbers).
*
* @param val - The value to check.
*/
function isSequence(val) {
return typeof val !== 'number';
}
/**
* Concatenate all `arguments` into a single array. Each argument can be either
* a single element or a sequence, which has a `length` property and supports
* element retrieval via sequence[ix].
*
* > concatArgs(1, [2, 3], Buffer.from([4,5]), new Uint8Array([6, 7]));
* [1,2,3,4,5,6,7]
*
* @param args - Concatenate of these args into a single array.
* @returns Array of concatenated arguments
*/
function concatArgs(...args) {
const ret = [];
args.forEach((arg) => {
if (isSequence(arg)) {
for (const j of arg) {
ret.push(j);
}
}
else {
ret.push(arg);
}
});
return ret;
}
exports.concatArgs = concatArgs;
//# sourceMappingURL=utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAc,EAAE,IAAc;IACrD,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE;QAC/B,OAAO,KAAK,CAAA;KACb;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE;YACvB,OAAO,KAAK,CAAA;SACb;KACF;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAXD,4BAWC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,GAAsB;IACxC,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAA;AAChC,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,UAAU,CAAC,GAAG,IAA8B;IAC1D,MAAM,GAAG,GAAa,EAAE,CAAA;IAExB,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QACnB,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;YACnB,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE;gBACnB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;aACZ;SACF;aAAM;YACL,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;SACd;IACH,CAAC,CAAC,CAAA;IACF,OAAO,GAAG,CAAA;AACZ,CAAC;AAbD,gCAaC"}
+65
View File
@@ -0,0 +1,65 @@
/**
* Codec class
*/
/// <reference types="node" />
declare class Codec {
private readonly _sha256;
private readonly _alphabet;
private readonly _codec;
constructor(options: {
sha256: (bytes: Uint8Array) => Buffer;
alphabet: string;
});
/**
* Encoder.
*
* @param bytes - Buffer of data to encode.
* @param opts - Options object including the version bytes and the expected length of the data to encode.
*/
encode(bytes: Buffer, opts: {
versions: number[];
expectedLength: number;
}): string;
/**
* Decoder.
*
* @param base58string - Base58Check-encoded string to decode.
* @param opts - Options object including the version byte(s) and the expected length of the data after decoding.
*/
decode(base58string: string, opts: {
versions: Array<number | number[]>;
expectedLength?: number;
versionTypes?: ['ed25519', 'secp256k1'];
}): {
version: number[];
bytes: Buffer;
type: 'ed25519' | 'secp256k1' | null;
};
encodeChecked(buffer: Buffer): string;
decodeChecked(base58string: string): Buffer;
private _encodeVersioned;
private _encodeRaw;
private _decodeRaw;
private _verifyCheckSum;
}
export declare const codec: Codec;
export declare function encodeSeed(entropy: Buffer, type: 'ed25519' | 'secp256k1'): string;
export declare function decodeSeed(seed: string, opts?: {
versionTypes: ['ed25519', 'secp256k1'];
versions: Array<number | number[]>;
expectedLength: number;
}): {
version: number[];
bytes: Buffer;
type: 'ed25519' | 'secp256k1' | null;
};
export declare function encodeAccountID(bytes: Buffer): string;
export declare const encodeAddress: typeof encodeAccountID;
export declare function decodeAccountID(accountId: string): Buffer;
export declare const decodeAddress: typeof decodeAccountID;
export declare function decodeNodePublic(base58string: string): Buffer;
export declare function encodeNodePublic(bytes: Buffer): string;
export declare function encodeAccountPublic(bytes: Buffer): string;
export declare function decodeAccountPublic(base58string: string): Buffer;
export declare function isValidClassicAddress(address: string): boolean;
export {};
+192
View File
@@ -0,0 +1,192 @@
"use strict";
/**
* Codec class
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidClassicAddress = exports.decodeAccountPublic = exports.encodeAccountPublic = exports.encodeNodePublic = exports.decodeNodePublic = exports.decodeAddress = exports.decodeAccountID = exports.encodeAddress = exports.encodeAccountID = exports.decodeSeed = exports.encodeSeed = exports.codec = void 0;
const baseCodec = require("base-x");
const createHash = require("create-hash");
const utils_1 = require("./utils");
class Codec {
constructor(options) {
this._sha256 = options.sha256;
this._alphabet = options.alphabet;
this._codec = baseCodec(this._alphabet);
}
/**
* Encoder.
*
* @param bytes - Buffer of data to encode.
* @param opts - Options object including the version bytes and the expected length of the data to encode.
*/
encode(bytes, opts) {
const versions = opts.versions;
return this._encodeVersioned(bytes, versions, opts.expectedLength);
}
/**
* Decoder.
*
* @param base58string - Base58Check-encoded string to decode.
* @param opts - Options object including the version byte(s) and the expected length of the data after decoding.
*/
/* eslint-disable max-lines-per-function --
* TODO refactor */
decode(base58string, opts) {
var _a;
const versions = opts.versions;
const types = opts.versionTypes;
const withoutSum = this.decodeChecked(base58string);
if (versions.length > 1 && !opts.expectedLength) {
throw new Error('expectedLength is required because there are >= 2 possible versions');
}
const versionLengthGuess = typeof versions[0] === 'number' ? 1 : versions[0].length;
const payloadLength = (_a = opts.expectedLength) !== null && _a !== void 0 ? _a : withoutSum.length - versionLengthGuess;
const versionBytes = withoutSum.slice(0, -payloadLength);
const payload = withoutSum.slice(-payloadLength);
for (let i = 0; i < versions.length; i++) {
/* eslint-disable @typescript-eslint/consistent-type-assertions --
* TODO refactor */
const version = Array.isArray(versions[i])
? versions[i]
: [versions[i]];
if ((0, utils_1.seqEqual)(versionBytes, version)) {
return {
version,
bytes: payload,
type: types ? types[i] : null,
};
}
/* eslint-enable @typescript-eslint/consistent-type-assertions */
}
throw new Error('version_invalid: version bytes do not match any of the provided version(s)');
}
encodeChecked(buffer) {
const check = this._sha256(this._sha256(buffer)).slice(0, 4);
return this._encodeRaw(Buffer.from((0, utils_1.concatArgs)(buffer, check)));
}
decodeChecked(base58string) {
const buffer = this._decodeRaw(base58string);
if (buffer.length < 5) {
throw new Error('invalid_input_size: decoded data must have length >= 5');
}
if (!this._verifyCheckSum(buffer)) {
throw new Error('checksum_invalid');
}
return buffer.slice(0, -4);
}
_encodeVersioned(bytes, versions, expectedLength) {
if (expectedLength && bytes.length !== expectedLength) {
throw new Error('unexpected_payload_length: bytes.length does not match expectedLength.' +
' Ensure that the bytes are a Buffer.');
}
return this.encodeChecked(Buffer.from((0, utils_1.concatArgs)(versions, bytes)));
}
_encodeRaw(bytes) {
return this._codec.encode(bytes);
}
/* eslint-enable max-lines-per-function */
_decodeRaw(base58string) {
return this._codec.decode(base58string);
}
_verifyCheckSum(bytes) {
const computed = this._sha256(this._sha256(bytes.slice(0, -4))).slice(0, 4);
const checksum = bytes.slice(-4);
return (0, utils_1.seqEqual)(computed, checksum);
}
}
/**
* XRP codec
*/
// base58 encodings: https://xrpl.org/base58-encodings.html
// Account address (20 bytes)
const ACCOUNT_ID = 0;
// Account public key (33 bytes)
const ACCOUNT_PUBLIC_KEY = 0x23;
// 33; Seed value (for secret keys) (16 bytes)
const FAMILY_SEED = 0x21;
// 28; Validation public key (33 bytes)
const NODE_PUBLIC = 0x1c;
// [1, 225, 75]
const ED25519_SEED = [0x01, 0xe1, 0x4b];
const codecOptions = {
sha256(bytes) {
return createHash('sha256').update(Buffer.from(bytes)).digest();
},
alphabet: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz',
};
const codecWithXrpAlphabet = new Codec(codecOptions);
exports.codec = codecWithXrpAlphabet;
// entropy is a Buffer of size 16
// type is 'ed25519' or 'secp256k1'
function encodeSeed(entropy, type) {
if (entropy.length !== 16) {
throw new Error('entropy must have length 16');
}
const opts = {
expectedLength: 16,
// for secp256k1, use `FAMILY_SEED`
versions: type === 'ed25519' ? ED25519_SEED : [FAMILY_SEED],
};
// prefixes entropy with version bytes
return codecWithXrpAlphabet.encode(entropy, opts);
}
exports.encodeSeed = encodeSeed;
function decodeSeed(seed, opts = {
versionTypes: ['ed25519', 'secp256k1'],
versions: [ED25519_SEED, FAMILY_SEED],
expectedLength: 16,
}) {
return codecWithXrpAlphabet.decode(seed, opts);
}
exports.decodeSeed = decodeSeed;
function encodeAccountID(bytes) {
const opts = { versions: [ACCOUNT_ID], expectedLength: 20 };
return codecWithXrpAlphabet.encode(bytes, opts);
}
exports.encodeAccountID = encodeAccountID;
/* eslint-disable import/no-unused-modules ---
* unclear why this is aliased but we should keep it in case someone else is
* importing it with the aliased name */
exports.encodeAddress = encodeAccountID;
/* eslint-enable import/no-unused-modules */
function decodeAccountID(accountId) {
const opts = { versions: [ACCOUNT_ID], expectedLength: 20 };
return codecWithXrpAlphabet.decode(accountId, opts).bytes;
}
exports.decodeAccountID = decodeAccountID;
/* eslint-disable import/no-unused-modules ---
* unclear why this is aliased but we should keep it in case someone else is
* importing it with the aliased name */
exports.decodeAddress = decodeAccountID;
/* eslint-enable import/no-unused-modules */
function decodeNodePublic(base58string) {
const opts = { versions: [NODE_PUBLIC], expectedLength: 33 };
return codecWithXrpAlphabet.decode(base58string, opts).bytes;
}
exports.decodeNodePublic = decodeNodePublic;
function encodeNodePublic(bytes) {
const opts = { versions: [NODE_PUBLIC], expectedLength: 33 };
return codecWithXrpAlphabet.encode(bytes, opts);
}
exports.encodeNodePublic = encodeNodePublic;
function encodeAccountPublic(bytes) {
const opts = { versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33 };
return codecWithXrpAlphabet.encode(bytes, opts);
}
exports.encodeAccountPublic = encodeAccountPublic;
function decodeAccountPublic(base58string) {
const opts = { versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33 };
return codecWithXrpAlphabet.decode(base58string, opts).bytes;
}
exports.decodeAccountPublic = decodeAccountPublic;
function isValidClassicAddress(address) {
try {
decodeAccountID(address);
}
catch (_error) {
return false;
}
return true;
}
exports.isValidClassicAddress = isValidClassicAddress;
//# sourceMappingURL=xrp-codec.js.map
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
{
"name": "ripple-address-codec",
"version": "4.2.5",
"description": "encodes/decodes base58 encoded XRP Ledger identifiers",
"files": [
"dist/*",
"build/*"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"license": "ISC",
"dependencies": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
},
"prepublish": "tsc -b",
"prepublishOnly": "tslint -b ./ && jest",
"scripts": {
"build": "tsc -b",
"test": "jest --verbose false --silent=false ./src/*.test.js",
"lint": "eslint . --ext .ts",
"clean": "rm -rf ./dist && rm -rf tsconfig.tsbuildinfo"
},
"prettier": "@xrplf/prettier-config",
"engines": {
"node": ">= 10"
},
"gitHead": "b3d3bc2f99c21336c32d234026ddff79f16e8194"
}