├── .github ├── dependabot.yml └── workflows │ └── nodejs.yml ├── .gitignore ├── .travis.yml ├── .vscode └── settings.json ├── HISTORY.md ├── LICENSE ├── README.md ├── examples └── bitcoin.js ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── index.test.ts ├── index.ts ├── utils.test.ts ├── utils.ts ├── xrp-codec.test.ts └── xrp-codec.ts ├── tsconfig.json └── tslint.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: "15:00" 8 | open-pull-requests-limit: 20 9 | ignore: 10 | - dependency-name: "@types/node" 11 | versions: 12 | - 14.14.25 13 | - 14.14.28 14 | - 14.14.32 15 | - dependency-name: typescript 16 | versions: 17 | - 4.2.2 18 | - dependency-name: ts-jest 19 | versions: 20 | - 26.5.0 21 | - 26.5.2 22 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | workflow_dispatch: 12 | 13 | jobs: 14 | build: 15 | 16 | runs-on: ubuntu-latest 17 | 18 | strategy: 19 | matrix: 20 | node-version: [10.x, 12.x, 13.x, 14.x] 21 | 22 | steps: 23 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 24 | - uses: actions/checkout@v2 25 | - name: Use Node.js ${{ matrix.node-version }} 26 | uses: actions/setup-node@v1 27 | with: 28 | node-version: ${{ matrix.node-version }} 29 | - run: npm install 30 | - run: npm run compile 31 | - run: npm test 32 | - run: npm run lint 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # .gitignore 2 | 3 | # Ignore vim swap files. 4 | *.swp 5 | 6 | # Ignore SCons support files. 7 | .sconsign.dblite 8 | 9 | # Ignore python compiled files. 10 | *.pyc 11 | 12 | # Ignore Macintosh Desktop Services Store files. 13 | .DS_Store 14 | 15 | # Ignore backup/temps 16 | *~ 17 | 18 | # Ignore object files. 19 | *.o 20 | build/ 21 | tags 22 | bin/rippled 23 | Debug/*.* 24 | Release/*.* 25 | 26 | # Ignore locally installed node_modules 27 | node_modules 28 | !test/node_modules 29 | 30 | # Ignore tmp directory. 31 | tmp 32 | 33 | # Ignore database directory. 34 | db/*.db 35 | db/*.db-* 36 | 37 | # Ignore customized configs 38 | rippled.cfg 39 | validators.txt 40 | test/config.js 41 | 42 | # Ignore coverage files 43 | /lib-cov 44 | /src-cov 45 | /coverage.html 46 | /coverage 47 | 48 | # Ignore IntelliJ files 49 | .idea 50 | 51 | # Ignore npm-debug 52 | npm-debug.log 53 | 54 | # Ignore dist folder 55 | dist/ 56 | 57 | # Ignore flow output directory 58 | out/ 59 | 60 | # Ignore perf test cache 61 | scripts/cache 62 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 10 4 | - 12 5 | - 13 6 | script: 7 | - npm run compile 8 | - npm test 9 | - npm run lint 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "secp256k1" 4 | ] 5 | } -------------------------------------------------------------------------------- /HISTORY.md: -------------------------------------------------------------------------------- 1 | # ripple-address-cod 2 | 3 | ## 4.1.3 (2021-05-10) 4 | 5 | * Update dependencies 6 | * Add `build` script as an alias for `compile` 7 | * Update README 8 | 9 | ## 4.1.2 (2021-01-11) 10 | 11 | * Internal dependencies 12 | * Update jest, ts-jest, typescript, lodash 13 | * Fix potential moderate severity vulnerabilities 14 | * Update @types/node, @types/jest, base-x 15 | * Docs 16 | * Update example for encoding test address 17 | * Document functions (#73) 18 | * xAddressToClassicAddress when there is no tag (#114) 19 | * Add README badges (#120) 20 | * Add LICENSE (#138) 21 | * Cleanup and polish 22 | * Add GitHub CI (#115) 23 | * Fix linting 24 | 25 | ## 4.1.1 (2020-04-03) 26 | 27 | * Require node v10+ 28 | * CI: Drop node 6 & 8 and add node 13 29 | * Update dependencies 30 | * Bump @types/node to 13.7.7 (#60) 31 | * Bump jest and ts-jest (#40) 32 | * Bump @types/jest to 25.1.2 (#51) 33 | * Bump ts-jest from 25.0.0 to 25.2.0 (#50) 34 | * Bump typescript from 3.7.5 to 3.8.3 (#61) 35 | * Update all dependencies in yarn.lock 36 | 37 | ## 4.1.0 (2020-01-22) 38 | 39 | * Throwable 'unexpected_payload_length' error: The message has been expanded with ' Ensure that the bytes are a Buffer.' 40 | * Docs (readme): Correct X-address to classic address example (#15) (thanks @RareData) 41 | 42 | ### New Features 43 | 44 | * `encodeAccountPublic` - Encode a public key, as for payment channels 45 | * `decodeAccountPublic` - Decode a public key, as for payment channels 46 | 47 | * Internal 48 | * Update dependencies: ts-jest, @types/jest, @types/node, typescript, tslint, 49 | base-x 50 | 51 | ## 4.0.0 (2019-10-08) 52 | 53 | ### Breaking Changes 54 | 55 | * `decodeAddress` has been renamed to `decodeAccountID` 56 | * `isValidAddress` has been renamed to `isValidClassicAddress` 57 | 58 | ### New Features 59 | 60 | * `classicAddressToXAddress` - Derive X-address from classic address, tag, and network ID 61 | * `encodeXAddress` - Encode account ID, tag, and network ID as an X-address 62 | * `xAddressToClassicAddress` - Decode an X-address to account ID, tag, and network ID 63 | * `decodeXAddress` - Convert X-address to classic address, tag, and network ID 64 | * `isValidXAddress` - Check whether an X-address (X...) is valid 65 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Ripple Labs Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ripple-address-codec 2 | 3 | This repository has been moved to: [https://github.com/XRPLF/xrpl.js/tree/develop/packages/ripple-address-codec](https://github.com/XRPLF/xrpl.js/tree/develop/packages/ripple-address-codec) 4 | -------------------------------------------------------------------------------- /examples/bitcoin.js: -------------------------------------------------------------------------------- 1 | var api = require('../'); 2 | var pubVersion = [0x04, 0x88, 0xB2, 0x1E]; 3 | var options = {version: pubVersion, alphabet: 'bitcoin'}; 4 | var key = 'xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6LBpB85b3D2yc8sfvZU521AAwdZafEz7mnzBBsz4wKY5e4cp9LB'; 5 | var decoded = api.decode(key, options); 6 | var reencoded = api.encode(decoded, options); 7 | console.log(key); 8 | // 'xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6LBpB85b3D2yc8sfvZU521AAwdZafEz7mnzBBsz4wKY5e4cp9LB' 9 | console.log(reencoded); 10 | // 'xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6LBpB85b3D2yc8sfvZU521AAwdZafEz7mnzBBsz4wKY5e4cp9LB' -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "roots": [ 3 | "/src" 4 | ], 5 | "transform": { 6 | "^.+\\.tsx?$": "ts-jest" 7 | }, 8 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ripple-address-codec", 3 | "version": "4.1.3", 4 | "description": "encodes/decodes base58 encoded XRP Ledger identifiers", 5 | "files": [ 6 | "dist/*", 7 | "build/*" 8 | ], 9 | "main": "dist/index.js", 10 | "types": "dist/index.d.ts", 11 | "license": "ISC", 12 | "dependencies": { 13 | "base-x": "3.0.9", 14 | "create-hash": "^1.1.2" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git://github.com/ripple/ripple-address-codec.git" 19 | }, 20 | "prepublish": "tsc", 21 | "prepublishOnly": "tslint -p ./ && jest", 22 | "scripts": { 23 | "build": "tsc", 24 | "compile": "tsc", 25 | "test": "jest", 26 | "lint": "tslint -p ./" 27 | }, 28 | "devDependencies": { 29 | "@types/jest": "^27.0.2", 30 | "@types/node": "^16.4.3", 31 | "jest": "^26.6.3", 32 | "ts-jest": "^26.4.4", 33 | "tslint": "^5.19.0", 34 | "tslint-eslint-rules": "^5.4.0", 35 | "typescript": "^4.4.4" 36 | }, 37 | "engines": { 38 | "node": ">= 10", 39 | "npm": ">=7.0.0" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | classicAddressToXAddress, 3 | xAddressToClassicAddress, 4 | isValidXAddress, 5 | encodeXAddress 6 | } from './index' 7 | 8 | const testCases = [ 9 | [ 10 | 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 11 | false, 12 | 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ', 13 | 'T719a5UwUCnEs54UsxG9CJYYDhwmFCqkr7wxCcNcfZ6p5GZ' 14 | ], 15 | [ 16 | 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 17 | 1, 18 | 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaGZMhc9YTE92ehJ2Fu', 19 | 'T719a5UwUCnEs54UsxG9CJYYDhwmFCvbJNZbi37gBGkRkbE' 20 | ], 21 | [ 22 | 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 23 | 14, 24 | 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaGo2K5VpXpmCqbV2gS', 25 | 'T719a5UwUCnEs54UsxG9CJYYDhwmFCvqXVCALUGJGSbNV3x' 26 | ], 27 | [ 28 | 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 29 | 11747, 30 | 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaLFuhLRuNXPrDeJd9A', 31 | 'T719a5UwUCnEs54UsxG9CJYYDhwmFCziiNHtUukubF2Mg6t' 32 | ], 33 | [ 34 | 'rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K', 35 | false, 36 | 'XVZVpQj8YSVpNyiwXYSqvQoQqgBttTxAZwMcuJd4xteQHyt', 37 | 'TVVrSWtmQQssgVcmoMBcFQZKKf56QscyWLKnUyiuZW8ALU4' 38 | ], 39 | [ 40 | 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', 41 | false, 42 | 'X7YenJqxv3L66CwhBSfd3N8RzGXxYqPopMGMsCcpho79rex', 43 | 'T77wVQzA8ntj9wvCTNiQpNYLT5hmhRsFyXDoMLqYC4BzQtV' 44 | ], 45 | [ 46 | 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', 47 | 58, 48 | 'X7YenJqxv3L66CwhBSfd3N8RzGXxYqV56ZkTCa9UCzgaao1', 49 | 'T77wVQzA8ntj9wvCTNiQpNYLT5hmhR9kej6uxm4jGcQD7rZ' 50 | ], 51 | [ 52 | 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', 53 | 23480, 54 | 'X7d3eHCXzwBeWrZec1yT24iZerQjYL8m8zCJ16ACxu1BrBY', 55 | 'T7YChPFWifjCAXLEtg5N74c7fSAYsvSokwcmBPBUZWhxH5P' 56 | ], 57 | [ 58 | 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', 59 | 11747, 60 | 'X7d3eHCXzwBeWrZec1yT24iZerQjYLo2CJf8oVC5CMWey5m', 61 | 'T7YChPFWifjCAXLEtg5N74c7fSAYsvTcc7nEfwuEEvn5Q4w' 62 | ], 63 | [ 64 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 65 | false, 66 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV5fdx1mHp98tDMoQXb', 67 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQn49b3qD26PK7FcGSKE' 68 | ], 69 | [ 70 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 71 | 0, 72 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV8AqEL4xcZj5whKbmc', 73 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnSy8RHqGHoGJ59spi2' 74 | ], 75 | [ 76 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 77 | 1, 78 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV8xvjGQTYPiAx6gwDC', 79 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnSz1uDimDdPYXzSpyw' 80 | ], 81 | [ 82 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 83 | 2, 84 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV8zpDURx7DzBCkrQE7', 85 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnTryP9tG9TW8GeMBmd' 86 | ], 87 | [ 88 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 89 | 32, 90 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtVoYiC9UvKfjKar4LJe', 91 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnT2oqaCDzMEuCDAj1j' 92 | ], 93 | [ 94 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 95 | 276, 96 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtVoKj3MnFGMXEFMnvJV', 97 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnTMgJJYfAbsiPsc6Zg' 98 | ], 99 | [ 100 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 101 | 65591, 102 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtVozpjdhPQVdt3ghaWw', 103 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQn7ryu2W6njw7mT1jmS' 104 | ], 105 | [ 106 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 107 | 16781933, 108 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtVqrDUk2vDpkTjPsY73', 109 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnVsw45sDtGHhLi27Qa' 110 | ], 111 | [ 112 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 113 | 4294967294, 114 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV1kAsixQTdMjbWi39u', 115 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnX8tDFQ53itLNqs6vU' 116 | ], 117 | [ 118 | 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 119 | 4294967295, 120 | 'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi', 121 | 'TVE26TYGhfLC7tQDno7G8dGtxSkYQnXoy6kSDh6rZzApc69' 122 | ], 123 | [ 124 | 'rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY', 125 | false, 126 | 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD2gYsjNFQLKYW33DzBm', 127 | 'TVd2rqMkYL2AyS97NdELcpeiprNBjwLZzuUG5rZnaewsahi' 128 | ], 129 | [ 130 | 'rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY', 131 | 0, 132 | 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD2m4Er6SnvjVLpMWPjR', 133 | 'TVd2rqMkYL2AyS97NdELcpeiprNBjwRQUBetPbyrvXSTuxU' 134 | ], 135 | [ 136 | 'rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY', 137 | 13371337, 138 | 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD2qwGkhgc48zzcx6Gkr', 139 | 'TVd2rqMkYL2AyS97NdELcpeiprNBjwVUDvp3vhpXbNhLwJi' 140 | ] 141 | ] 142 | 143 | ;[false, true].forEach(isTestAddress => { 144 | const MAX_32_BIT_UNSIGNED_INT = 4294967295 145 | const network = isTestAddress ? ' (test)' : ' (main)' 146 | 147 | for (const i in testCases) { 148 | const testCase = testCases[i] 149 | const classicAddress = testCase[0] as string 150 | const tag = testCase[1] !== false ? testCase[1] as number : false 151 | const xAddress = isTestAddress ? testCase[3] as string : testCase[2] as string 152 | test(`Converts ${classicAddress}${tag ? ':' + tag : ''} to ${xAddress}${network}`, () => { 153 | expect(classicAddressToXAddress(classicAddress, tag, isTestAddress)).toBe(xAddress) 154 | const myClassicAddress = xAddressToClassicAddress(xAddress) 155 | expect(myClassicAddress).toEqual({ 156 | classicAddress, 157 | tag, 158 | test: isTestAddress 159 | }) 160 | expect(isValidXAddress(xAddress)).toBe(true) 161 | }) 162 | } 163 | 164 | { 165 | const classicAddress = 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf' 166 | const tag = MAX_32_BIT_UNSIGNED_INT + 1 167 | 168 | test(`Converting ${classicAddress}:${tag}${network} throws`, () => { 169 | expect(() => { 170 | classicAddressToXAddress(classicAddress, tag, isTestAddress) 171 | }).toThrowError(new Error('Invalid tag')) 172 | }) 173 | } 174 | 175 | { 176 | const classicAddress = 'r' 177 | test(`Invalid classic address: Converting ${classicAddress}${network} throws`, () => { 178 | expect(() => { 179 | classicAddressToXAddress(classicAddress, false, isTestAddress) 180 | }).toThrowError(new Error('invalid_input_size: decoded data must have length >= 5')) 181 | }) 182 | } 183 | 184 | { 185 | const highAndLowAccounts = [ 186 | Buffer.from('00'.repeat(20), 'hex'), 187 | Buffer.from('00'.repeat(19) + '01', 'hex'), 188 | Buffer.from('01'.repeat(20), 'hex'), 189 | Buffer.from('FF'.repeat(20), 'hex') 190 | ] 191 | 192 | highAndLowAccounts.forEach(accountId => { 193 | [false, 0, 1, MAX_32_BIT_UNSIGNED_INT].forEach(t => { 194 | const tag = (t as number | false) 195 | const xAddress = encodeXAddress(accountId, tag, isTestAddress) 196 | test(`Encoding ${accountId.toString('hex')}${tag ? ':' + tag : ''} to ${xAddress} has expected length`, () => { 197 | expect(xAddress.length).toBe(47) 198 | }) 199 | }) 200 | }) 201 | } 202 | }) 203 | 204 | { 205 | const xAddress = 'XVLhHMPHU98es4dbozjVtdWzVrDjtV5fdx1mHp98tDMoQXa' 206 | test(`Invalid X-address (bad checksum): Converting ${xAddress} throws`, () => { 207 | expect(() => { 208 | xAddressToClassicAddress(xAddress) 209 | }).toThrowError(new Error('checksum_invalid')) 210 | }) 211 | } 212 | 213 | { 214 | const xAddress = 'dGzKGt8CVpWoa8aWL1k18tAdy9Won3PxynvbbpkAqp3V47g' 215 | test(`Invalid X-address (bad prefix): Converting ${xAddress} throws`, () => { 216 | expect(() => { 217 | xAddressToClassicAddress(xAddress) 218 | }).toThrowError(new Error('Invalid X-address: bad prefix')) 219 | }) 220 | } 221 | 222 | test(`Invalid X-address (64-bit tag) throws`, () => { 223 | expect(() => { 224 | // Encoded from: 225 | // { 226 | // classicAddress: 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 227 | // tag: MAX_32_BIT_UNSIGNED_INT + 1 228 | // } 229 | xAddressToClassicAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8zeUygYrCgrPh') 230 | }).toThrowError('Unsupported X-address') 231 | }) 232 | 233 | test(`Invalid Account ID throws`, () => { 234 | expect(() => { 235 | encodeXAddress(Buffer.from('00'.repeat(19), 'hex'), false, false) 236 | }).toThrowError('Account ID must be 20 bytes') 237 | }) 238 | 239 | test(`isValidXAddress returns false for invalid X-address`, () => { 240 | expect(isValidXAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8zeUygYrCgrPh')).toBe(false) 241 | }) 242 | 243 | test(`Converts X7AcgcsBL6XDcUb... to r9cZA1mLK5R5A... and tag: false`, () => { 244 | const classicAddress = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59' 245 | const tag = false 246 | const xAddress = 'X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ' 247 | const isTestAddress = false 248 | expect(classicAddressToXAddress(classicAddress, tag, isTestAddress)).toBe(xAddress) 249 | const myClassicAddress = xAddressToClassicAddress(xAddress) 250 | expect(myClassicAddress).toEqual({ 251 | classicAddress, 252 | tag, 253 | test: isTestAddress 254 | }) 255 | expect(isValidXAddress(xAddress)).toBe(true) 256 | 257 | // Notice that converting an X-address to a classic address has `result.tag === false` (not undefined) 258 | expect(myClassicAddress.tag).toEqual(false) 259 | }) 260 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | codec, 3 | encodeSeed, 4 | decodeSeed, 5 | encodeAccountID, 6 | decodeAccountID, 7 | encodeNodePublic, 8 | decodeNodePublic, 9 | encodeAccountPublic, 10 | decodeAccountPublic, 11 | isValidClassicAddress 12 | } from './xrp-codec' 13 | import * as assert from 'assert' 14 | 15 | const PREFIX_BYTES = { 16 | MAIN: Buffer.from([0x05, 0x44]), // 5, 68 17 | TEST: Buffer.from([0x04, 0x93]) // 4, 147 18 | } 19 | 20 | function classicAddressToXAddress(classicAddress: string, tag: number | false, test: boolean): string { 21 | const accountId = decodeAccountID(classicAddress) 22 | return encodeXAddress(accountId, tag, test) 23 | } 24 | 25 | function encodeXAddress(accountId: Buffer, tag: number | false, test: boolean): string { 26 | if (accountId.length !== 20) { 27 | // RIPEMD160 is 160 bits = 20 bytes 28 | throw new Error('Account ID must be 20 bytes') 29 | } 30 | const MAX_32_BIT_UNSIGNED_INT = 4294967295 31 | const flag = tag === false ? 0 : tag <= MAX_32_BIT_UNSIGNED_INT ? 1 : 2 32 | if (flag === 2) { 33 | throw new Error('Invalid tag') 34 | } 35 | if (tag === false) { 36 | tag = 0 37 | } 38 | const bytes = Buffer.concat( 39 | [ 40 | test ? PREFIX_BYTES.TEST : PREFIX_BYTES.MAIN, 41 | accountId, 42 | Buffer.from( 43 | [ 44 | flag, // 0x00 if no tag, 0x01 if 32-bit tag 45 | tag & 0xff, // first byte 46 | (tag >> 8) & 0xff, // second byte 47 | (tag >> 16) & 0xff, // third byte 48 | (tag >> 24) & 0xff, // fourth byte 49 | 0, 0, 0, 0 // four zero bytes (reserved for 64-bit tags) 50 | ] 51 | ) 52 | ] 53 | ) 54 | const xAddress = codec.encodeChecked(bytes) 55 | return xAddress 56 | } 57 | 58 | function xAddressToClassicAddress(xAddress: string): {classicAddress: string, tag: number | false, test: boolean} { 59 | const { 60 | accountId, 61 | tag, 62 | test 63 | } = decodeXAddress(xAddress) 64 | const classicAddress = encodeAccountID(accountId) 65 | return { 66 | classicAddress, 67 | tag, 68 | test 69 | } 70 | } 71 | 72 | function decodeXAddress(xAddress: string): {accountId: Buffer, tag: number | false, test: boolean} { 73 | const decoded = codec.decodeChecked(xAddress) 74 | const test = isBufferForTestAddress(decoded) 75 | const accountId = decoded.slice(2, 22) 76 | const tag = tagFromBuffer(decoded) 77 | return { 78 | accountId, 79 | tag, 80 | test 81 | } 82 | } 83 | 84 | function isBufferForTestAddress(buf: Buffer): boolean { 85 | const decodedPrefix = buf.slice(0, 2) 86 | if (PREFIX_BYTES.MAIN.equals(decodedPrefix)) { 87 | return false 88 | } else if (PREFIX_BYTES.TEST.equals(decodedPrefix)) { 89 | return true 90 | } else { 91 | throw new Error('Invalid X-address: bad prefix') 92 | } 93 | } 94 | 95 | function tagFromBuffer(buf: Buffer): number | false { 96 | const flag = buf[22] 97 | if (flag >= 2) { 98 | // No support for 64-bit tags at this time 99 | throw new Error('Unsupported X-address') 100 | } 101 | if (flag === 1) { 102 | // Little-endian to big-endian 103 | return buf[23] + buf[24] * 0x100 + buf[25] * 0x10000 + buf[26] * 0x1000000 104 | } 105 | assert.strictEqual(flag, 0, 'flag must be zero to indicate no tag') 106 | assert.ok(Buffer.from('0000000000000000', 'hex').equals(buf.slice(23, 23 + 8)), 107 | 'remaining bytes must be zero') 108 | return false 109 | } 110 | 111 | function isValidXAddress(xAddress: string): boolean { 112 | try { 113 | decodeXAddress(xAddress) 114 | } catch (e) { 115 | return false 116 | } 117 | return true 118 | } 119 | 120 | export { 121 | codec, // Codec with XRP alphabet 122 | encodeSeed, // Encode entropy as a "seed" 123 | decodeSeed, // Decode a seed into an object with its version, type, and bytes 124 | encodeAccountID, // Encode bytes as a classic address (r...) 125 | decodeAccountID, // Decode a classic address to its raw bytes 126 | encodeNodePublic, // Encode bytes to XRP Ledger node public key format 127 | decodeNodePublic, // Decode an XRP Ledger node public key into its raw bytes 128 | encodeAccountPublic, // Encode a public key, as for payment channels 129 | decodeAccountPublic, // Decode a public key, as for payment channels 130 | isValidClassicAddress, // Check whether a classic address (r...) is valid 131 | classicAddressToXAddress, // Derive X-address from classic address, tag, and network ID 132 | encodeXAddress, // Encode account ID, tag, and network ID to X-address 133 | xAddressToClassicAddress, // Decode X-address to account ID, tag, and network ID 134 | decodeXAddress, // Convert X-address to classic address, tag, and network ID 135 | isValidXAddress // Check whether an X-address (X...) is valid 136 | } 137 | -------------------------------------------------------------------------------- /src/utils.test.ts: -------------------------------------------------------------------------------- 1 | import {seqEqual, concatArgs} from './utils' 2 | 3 | test('two sequences are equal', () => { 4 | expect(seqEqual([1, 2, 3], [1, 2, 3])).toBe(true) 5 | }) 6 | 7 | test('elements must be in the same order', () => { 8 | expect(seqEqual([3, 2, 1], [1, 2, 3])).toBe(false) 9 | }) 10 | 11 | test('sequences do not need to be the same type', () => { 12 | expect(seqEqual(Buffer.from([1, 2, 3]), [1, 2, 3])).toBe(true) 13 | expect(seqEqual(Buffer.from([1, 2, 3]), new Uint8Array([1, 2, 3]))).toBe(true) 14 | }) 15 | 16 | test('sequences with a single element', () => { 17 | expect(seqEqual(Buffer.from([1]), [1])).toBe(true) 18 | expect(seqEqual(Buffer.from([1]), new Uint8Array([1]))).toBe(true) 19 | }) 20 | 21 | test('empty sequences', () => { 22 | expect(seqEqual(Buffer.from([]), [])).toBe(true) 23 | expect(seqEqual(Buffer.from([]), new Uint8Array([]))).toBe(true) 24 | }) 25 | 26 | test('plain numbers are concatenated', () => { 27 | expect(concatArgs(10, 20, 30, 40)).toStrictEqual([10, 20, 30, 40]) 28 | }) 29 | 30 | test('a variety of values are concatenated', () => { 31 | expect(concatArgs(1, [2, 3], Buffer.from([4,5]), new Uint8Array([6, 7]))).toStrictEqual([1,2,3,4,5,6,7]) 32 | }) 33 | 34 | test('a single value is returned as an array', () => { 35 | expect(concatArgs(Buffer.from([7]))).toStrictEqual([7]) 36 | }) 37 | 38 | test('no arguments returns an empty array', () => { 39 | expect(concatArgs()).toStrictEqual([]) 40 | }) 41 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | type Sequence = number[] | Buffer | Uint8Array 2 | 3 | /** 4 | * Check whether two sequences (e.g. arrays of numbers) are equal. 5 | * 6 | * @param arr1 One of the arrays to compare. 7 | * @param arr2 The other array to compare. 8 | */ 9 | export function seqEqual(arr1: Sequence, arr2: Sequence): boolean { 10 | if (arr1.length !== arr2.length) { 11 | return false 12 | } 13 | 14 | for (let i = 0; i < arr1.length; i++) { 15 | if (arr1[i] !== arr2[i]) { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | 22 | /** 23 | * Check whether a value is a sequence (e.g. array of numbers). 24 | * 25 | * @param val The value to check. 26 | */ 27 | function isSequence(val: Sequence | number): val is Sequence { 28 | return (val as Sequence).length !== undefined 29 | } 30 | 31 | /** 32 | * Concatenate all `arguments` into a single array. Each argument can be either 33 | * a single element or a sequence, which has a `length` property and supports 34 | * element retrieval via sequence[ix]. 35 | * 36 | * > concatArgs(1, [2, 3], Buffer.from([4,5]), new Uint8Array([6, 7])); 37 | * [1,2,3,4,5,6,7] 38 | * 39 | * @returns {number[]} Array of concatenated arguments 40 | */ 41 | export function concatArgs(...args: (number | Sequence)[]): number[] { 42 | const ret: number[] = [] 43 | 44 | args.forEach(function (arg) { 45 | if (isSequence(arg)) { 46 | for (let j = 0; j < arg.length; j++) { 47 | ret.push(arg[j]) 48 | } 49 | } else { 50 | ret.push(arg) 51 | } 52 | }) 53 | return ret 54 | } 55 | -------------------------------------------------------------------------------- /src/xrp-codec.test.ts: -------------------------------------------------------------------------------- 1 | import * as api from './xrp-codec' 2 | 3 | function toHex(bytes: Buffer) { 4 | return Buffer.from(bytes).toString('hex').toUpperCase() 5 | } 6 | 7 | function toBytes(hex: string) { 8 | return Buffer.from(hex, 'hex') 9 | } 10 | 11 | /** 12 | * Create a test case for encoding data and a test case for decoding data. 13 | * 14 | * @param encoder Encoder function to test 15 | * @param decoder Decoder function to test 16 | * @param base58 Base58-encoded string to decode 17 | * @param hex Hexadecimal representation of expected decoded data 18 | */ 19 | function makeEncodeDecodeTest(encoder: Function, decoder: Function, base58: string, hex: string) { 20 | test(`can translate between ${hex} and ${base58}`, function() { 21 | const actual = encoder(toBytes(hex)) 22 | expect(actual).toBe(base58) 23 | }) 24 | test(`can translate between ${base58} and ${hex})`, function() { 25 | const buf = decoder(base58) 26 | expect(toHex(buf)).toBe(hex) 27 | }) 28 | } 29 | 30 | makeEncodeDecodeTest(api.encodeAccountID, api.decodeAccountID, 'rJrRMgiRgrU6hDF4pgu5DXQdWyPbY35ErN', 31 | 'BA8E78626EE42C41B46D46C3048DF3A1C3C87072') 32 | 33 | makeEncodeDecodeTest(api.encodeNodePublic, api.decodeNodePublic, 34 | 'n9MXXueo837zYH36DvMc13BwHcqtfAWNJY5czWVbp7uYTj7x17TH', 35 | '0388E5BA87A000CB807240DF8C848EB0B5FFA5C8E5A521BC8E105C0F0A44217828') 36 | 37 | makeEncodeDecodeTest(api.encodeAccountPublic, api.decodeAccountPublic, 38 | 'aB44YfzW24VDEJQ2UuLPV2PvqcPCSoLnL7y5M1EzhdW4LnK5xMS3', 39 | '023693F15967AE357D0327974AD46FE3C127113B1110D6044FD41E723689F81CC6') 40 | 41 | test('can decode arbitrary seeds', function() { 42 | const decoded = api.decodeSeed('sEdTM1uX8pu2do5XvTnutH6HsouMaM2') 43 | expect(toHex(decoded.bytes)).toBe('4C3A1D213FBDFB14C7C28D609469B341') 44 | expect(decoded.type).toBe('ed25519') 45 | 46 | const decoded2 = api.decodeSeed('sn259rEFXrQrWyx3Q7XneWcwV6dfL') 47 | expect(toHex(decoded2.bytes)).toBe('CF2DE378FBDD7E2EE87D486DFB5A7BFF') 48 | expect(decoded2.type).toBe('secp256k1') 49 | }) 50 | 51 | test('can pass a type as second arg to encodeSeed', function() { 52 | const edSeed = 'sEdTM1uX8pu2do5XvTnutH6HsouMaM2' 53 | const decoded = api.decodeSeed(edSeed) 54 | const type = 'ed25519' 55 | expect(toHex(decoded.bytes)).toBe('4C3A1D213FBDFB14C7C28D609469B341') 56 | expect(decoded.type).toBe(type) 57 | expect(api.encodeSeed(decoded.bytes, type)).toBe(edSeed) 58 | }) 59 | 60 | test('isValidClassicAddress - secp256k1 address valid', function() { 61 | expect(api.isValidClassicAddress('rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1')).toBe(true) 62 | }) 63 | 64 | test('isValidClassicAddress - ed25519 address valid', function() { 65 | expect(api.isValidClassicAddress('rLUEXYuLiQptky37CqLcm9USQpPiz5rkpD')).toBe(true) 66 | }) 67 | 68 | test('isValidClassicAddress - invalid', function() { 69 | expect(api.isValidClassicAddress('rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw2')).toBe(false) 70 | }) 71 | 72 | test('isValidClassicAddress - empty', function() { 73 | expect(api.isValidClassicAddress('')).toBe(false) 74 | }) 75 | 76 | describe('encodeSeed', function() { 77 | 78 | it('encodes a secp256k1 seed', function() { 79 | const result = api.encodeSeed(Buffer.from('CF2DE378FBDD7E2EE87D486DFB5A7BFF', 'hex'), 'secp256k1') 80 | expect(result).toBe('sn259rEFXrQrWyx3Q7XneWcwV6dfL') 81 | }) 82 | 83 | it('encodes low secp256k1 seed', function() { 84 | const result = api.encodeSeed(Buffer.from('00000000000000000000000000000000', 'hex'), 'secp256k1') 85 | expect(result).toBe('sp6JS7f14BuwFY8Mw6bTtLKWauoUs') 86 | }) 87 | 88 | it('encodes high secp256k1 seed', function() { 89 | const result = api.encodeSeed(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 'hex'), 'secp256k1') 90 | expect(result).toBe('saGwBRReqUNKuWNLpUAq8i8NkXEPN') 91 | }) 92 | 93 | it('encodes an ed25519 seed', function() { 94 | const result = api.encodeSeed(Buffer.from('4C3A1D213FBDFB14C7C28D609469B341', 'hex'), 'ed25519') 95 | expect(result).toBe('sEdTM1uX8pu2do5XvTnutH6HsouMaM2') 96 | }) 97 | 98 | it('encodes low ed25519 seed', function() { 99 | const result = api.encodeSeed(Buffer.from('00000000000000000000000000000000', 'hex'), 'ed25519') 100 | expect(result).toBe('sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE') 101 | }) 102 | 103 | it('encodes high ed25519 seed', function() { 104 | const result = api.encodeSeed(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 'hex'), 'ed25519') 105 | expect(result).toBe('sEdV19BLfeQeKdEXyYA4NhjPJe6XBfG') 106 | }) 107 | 108 | test('attempting to encode a seed with less than 16 bytes of entropy throws', function() { 109 | expect(() => { 110 | api.encodeSeed(Buffer.from('CF2DE378FBDD7E2EE87D486DFB5A7B', 'hex'), 'secp256k1') 111 | }).toThrow('entropy must have length 16') 112 | }) 113 | 114 | test('attempting to encode a seed with more than 16 bytes of entropy throws', function() { 115 | expect(() => { 116 | api.encodeSeed(Buffer.from('CF2DE378FBDD7E2EE87D486DFB5A7BFFFF', 'hex'), 'secp256k1') 117 | }).toThrow('entropy must have length 16') 118 | }) 119 | }) 120 | 121 | describe('decodeSeed', function() { 122 | 123 | it('can decode an Ed25519 seed', function() { 124 | const decoded = api.decodeSeed('sEdTM1uX8pu2do5XvTnutH6HsouMaM2') 125 | expect(toHex(decoded.bytes)).toBe('4C3A1D213FBDFB14C7C28D609469B341') 126 | expect(decoded.type).toBe('ed25519') 127 | }) 128 | 129 | it('can decode a secp256k1 seed', function() { 130 | const decoded = api.decodeSeed('sn259rEFXrQrWyx3Q7XneWcwV6dfL') 131 | expect(toHex(decoded.bytes)).toBe('CF2DE378FBDD7E2EE87D486DFB5A7BFF') 132 | expect(decoded.type).toBe('secp256k1') 133 | }) 134 | }) 135 | 136 | describe('encodeAccountID', function() { 137 | 138 | it('can encode an AccountID', function() { 139 | const encoded = api.encodeAccountID(Buffer.from('BA8E78626EE42C41B46D46C3048DF3A1C3C87072', 'hex')) 140 | expect(encoded).toBe('rJrRMgiRgrU6hDF4pgu5DXQdWyPbY35ErN') 141 | }) 142 | 143 | test('unexpected length should throw', function() { 144 | expect(() => { 145 | api.encodeAccountID(Buffer.from('ABCDEF', 'hex')) 146 | }).toThrow( 147 | 'unexpected_payload_length: bytes.length does not match expectedLength' 148 | ) 149 | }) 150 | }) 151 | 152 | describe('decodeNodePublic', function() { 153 | 154 | it('can decode a NodePublic', function() { 155 | const decoded = api.decodeNodePublic('n9MXXueo837zYH36DvMc13BwHcqtfAWNJY5czWVbp7uYTj7x17TH') 156 | expect(toHex(decoded)).toBe('0388E5BA87A000CB807240DF8C848EB0B5FFA5C8E5A521BC8E105C0F0A44217828') 157 | }) 158 | }) 159 | 160 | test('encodes 123456789 with version byte of 0', () => { 161 | expect(api.codec.encode(Buffer.from('123456789'), { 162 | versions: [0], 163 | expectedLength: 9 164 | })).toBe('rnaC7gW34M77Kneb78s') 165 | }) 166 | 167 | test('multiple versions with no expected length should throw', () => { 168 | expect(() => { 169 | api.codec.decode('rnaC7gW34M77Kneb78s', { 170 | versions: [0, 1] 171 | }) 172 | }).toThrow('expectedLength is required because there are >= 2 possible versions') 173 | }) 174 | 175 | test('attempting to decode data with length < 5 should throw', () => { 176 | expect(() => { 177 | api.codec.decode('1234', { 178 | versions: [0] 179 | }) 180 | }).toThrow('invalid_input_size: decoded data must have length >= 5') 181 | }) 182 | 183 | test('attempting to decode data with unexpected version should throw', () => { 184 | expect(() => { 185 | api.codec.decode('rnaC7gW34M77Kneb78s', { 186 | versions: [2] 187 | }) 188 | }).toThrow('version_invalid: version bytes do not match any of the provided version(s)') 189 | }) 190 | 191 | test('invalid checksum should throw', () => { 192 | expect(() => { 193 | api.codec.decode('123456789', { 194 | versions: [0, 1] 195 | }) 196 | }).toThrow('checksum_invalid') 197 | }) 198 | 199 | test('empty payload should throw', () => { 200 | expect(() => { 201 | api.codec.decode('', { 202 | versions: [0, 1] 203 | }) 204 | }).toThrow('invalid_input_size: decoded data must have length >= 5') 205 | }) 206 | 207 | test('decode data', () => { 208 | expect(api.codec.decode('rnaC7gW34M77Kneb78s', { 209 | versions: [0] 210 | })).toStrictEqual({ 211 | version: [0], 212 | bytes: Buffer.from('123456789'), 213 | type: null 214 | }) 215 | }) 216 | 217 | test('decode data with expected length', function() { 218 | expect(api.codec.decode('rnaC7gW34M77Kneb78s', { 219 | versions: [0], 220 | expectedLength: 9 221 | }) 222 | ).toStrictEqual({ 223 | version: [0], 224 | bytes: Buffer.from('123456789'), 225 | type: null 226 | }) 227 | }) 228 | 229 | test('decode data with wrong expected length should throw', function() { 230 | expect(() => { 231 | api.codec.decode('rnaC7gW34M77Kneb78s', { 232 | versions: [0], 233 | expectedLength: 8 234 | }) 235 | }).toThrow( 236 | 'version_invalid: version bytes do not match any of the provided version(s)' 237 | ) 238 | expect(() => { 239 | api.codec.decode('rnaC7gW34M77Kneb78s', { 240 | versions: [0], 241 | expectedLength: 10 242 | }) 243 | }).toThrow( 244 | 'version_invalid: version bytes do not match any of the provided version(s)' 245 | ) 246 | }) 247 | -------------------------------------------------------------------------------- /src/xrp-codec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Codec class 3 | */ 4 | 5 | import * as baseCodec from 'base-x' 6 | import {seqEqual, concatArgs} from './utils' 7 | 8 | class Codec { 9 | sha256: (bytes: Uint8Array) => Buffer 10 | alphabet: string 11 | codec: any 12 | base: number 13 | 14 | constructor(options: { 15 | sha256: (bytes: Uint8Array) => Buffer, 16 | alphabet: string 17 | }) { 18 | this.sha256 = options.sha256 19 | this.alphabet = options.alphabet 20 | this.codec = baseCodec(this.alphabet) 21 | this.base = this.alphabet.length 22 | } 23 | 24 | /** 25 | * Encoder. 26 | * 27 | * @param bytes Buffer of data to encode. 28 | * @param opts Options object including the version bytes and the expected length of the data to encode. 29 | */ 30 | encode(bytes: Buffer, opts: { 31 | versions: number[], 32 | expectedLength: number 33 | }): string { 34 | const versions = opts.versions 35 | return this.encodeVersioned(bytes, versions, opts.expectedLength) 36 | } 37 | 38 | encodeVersioned(bytes: Buffer, versions: number[], expectedLength: number): string { 39 | if (expectedLength && bytes.length !== expectedLength) { 40 | throw new Error('unexpected_payload_length: bytes.length does not match expectedLength.' + 41 | ' Ensure that the bytes are a Buffer.') 42 | } 43 | return this.encodeChecked(Buffer.from(concatArgs(versions, bytes))) 44 | } 45 | 46 | encodeChecked(buffer: Buffer): string { 47 | const check = this.sha256(this.sha256(buffer)).slice(0, 4) 48 | return this.encodeRaw(Buffer.from(concatArgs(buffer, check))) 49 | } 50 | 51 | encodeRaw(bytes: Buffer): string { 52 | return this.codec.encode(bytes) 53 | } 54 | 55 | /** 56 | * Decoder. 57 | * 58 | * @param base58string Base58Check-encoded string to decode. 59 | * @param opts Options object including the version byte(s) and the expected length of the data after decoding. 60 | */ 61 | decode(base58string: string, opts: { 62 | versions: (number | number[])[], 63 | expectedLength?: number, 64 | versionTypes?: ['ed25519', 'secp256k1'] 65 | }): { 66 | version: number[], 67 | bytes: Buffer, 68 | type: string | null 69 | } { 70 | const versions = opts.versions 71 | const types = opts.versionTypes 72 | 73 | const withoutSum = this.decodeChecked(base58string) 74 | 75 | if (versions.length > 1 && !opts.expectedLength) { 76 | throw new Error('expectedLength is required because there are >= 2 possible versions') 77 | } 78 | const versionLengthGuess = typeof versions[0] === 'number' ? 1 : (versions[0] as number[]).length 79 | const payloadLength = opts.expectedLength || withoutSum.length - versionLengthGuess 80 | const versionBytes = withoutSum.slice(0, -payloadLength) 81 | const payload = withoutSum.slice(-payloadLength) 82 | 83 | for (let i = 0; i < versions.length; i++) { 84 | const version: number[] = Array.isArray(versions[i]) ? versions[i] as number[] : [versions[i] as number] 85 | if (seqEqual(versionBytes, version)) { 86 | return { 87 | version, 88 | bytes: payload, 89 | type: types ? types[i] : null 90 | } 91 | } 92 | } 93 | 94 | throw new Error('version_invalid: version bytes do not match any of the provided version(s)') 95 | } 96 | 97 | decodeChecked(base58string: string): Buffer { 98 | const buffer = this.decodeRaw(base58string) 99 | if (buffer.length < 5) { 100 | throw new Error('invalid_input_size: decoded data must have length >= 5') 101 | } 102 | if (!this.verifyCheckSum(buffer)) { 103 | throw new Error('checksum_invalid') 104 | } 105 | return buffer.slice(0, -4) 106 | } 107 | 108 | decodeRaw(base58string: string): Buffer { 109 | return this.codec.decode(base58string) 110 | } 111 | 112 | verifyCheckSum(bytes: Buffer): boolean { 113 | const computed = this.sha256(this.sha256(bytes.slice(0, -4))).slice(0, 4) 114 | const checksum = bytes.slice(-4) 115 | return seqEqual(computed, checksum) 116 | } 117 | } 118 | 119 | /** 120 | * XRP codec 121 | */ 122 | 123 | // Pure JavaScript hash functions in the browser, native hash functions in Node.js 124 | const createHash = require('create-hash') 125 | 126 | // base58 encodings: https://xrpl.org/base58-encodings.html 127 | const ACCOUNT_ID = 0 // Account address (20 bytes) 128 | const ACCOUNT_PUBLIC_KEY = 0x23 // Account public key (33 bytes) 129 | const FAMILY_SEED = 0x21 // 33; Seed value (for secret keys) (16 bytes) 130 | const NODE_PUBLIC = 0x1C // 28; Validation public key (33 bytes) 131 | 132 | const ED25519_SEED = [0x01, 0xE1, 0x4B] // [1, 225, 75] 133 | 134 | const codecOptions = { 135 | sha256: function(bytes: Uint8Array) { 136 | return createHash('sha256').update(Buffer.from(bytes)).digest() 137 | }, 138 | alphabet: 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz' 139 | } 140 | 141 | const codecWithXrpAlphabet = new Codec(codecOptions) 142 | 143 | export const codec = codecWithXrpAlphabet 144 | 145 | // entropy is a Buffer of size 16 146 | // type is 'ed25519' or 'secp256k1' 147 | export function encodeSeed(entropy: Buffer, type: 'ed25519' | 'secp256k1'): string { 148 | if (entropy.length !== 16) { 149 | throw new Error('entropy must have length 16') 150 | } 151 | const opts = { 152 | expectedLength: 16, 153 | 154 | // for secp256k1, use `FAMILY_SEED` 155 | versions: type === 'ed25519' ? ED25519_SEED : [FAMILY_SEED] 156 | } 157 | 158 | // prefixes entropy with version bytes 159 | return codecWithXrpAlphabet.encode(entropy, opts) 160 | } 161 | 162 | export function decodeSeed(seed: string, opts: { 163 | versionTypes: ['ed25519', 'secp256k1'], 164 | versions: (number | number[])[] 165 | expectedLength: number 166 | } = { 167 | versionTypes: ['ed25519', 'secp256k1'], 168 | versions: [ED25519_SEED, FAMILY_SEED], 169 | expectedLength: 16 170 | }) { 171 | return codecWithXrpAlphabet.decode(seed, opts) 172 | } 173 | 174 | export function encodeAccountID(bytes: Buffer): string { 175 | const opts = {versions: [ACCOUNT_ID], expectedLength: 20} 176 | return codecWithXrpAlphabet.encode(bytes, opts) 177 | } 178 | 179 | export const encodeAddress = encodeAccountID 180 | 181 | export function decodeAccountID(accountId: string): Buffer { 182 | const opts = {versions: [ACCOUNT_ID], expectedLength: 20} 183 | return codecWithXrpAlphabet.decode(accountId, opts).bytes 184 | } 185 | 186 | export const decodeAddress = decodeAccountID 187 | 188 | export function decodeNodePublic(base58string: string): Buffer { 189 | const opts = {versions: [NODE_PUBLIC], expectedLength: 33} 190 | return codecWithXrpAlphabet.decode(base58string, opts).bytes 191 | } 192 | 193 | export function encodeNodePublic(bytes: Buffer): string { 194 | const opts = {versions: [NODE_PUBLIC], expectedLength: 33} 195 | return codecWithXrpAlphabet.encode(bytes, opts) 196 | } 197 | 198 | export function encodeAccountPublic(bytes: Buffer): string { 199 | const opts = {versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33} 200 | return codecWithXrpAlphabet.encode(bytes, opts) 201 | } 202 | 203 | export function decodeAccountPublic(base58string: string): Buffer { 204 | const opts = {versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33} 205 | return codecWithXrpAlphabet.decode(base58string, opts).bytes 206 | } 207 | 208 | export function isValidClassicAddress(address: string): boolean { 209 | try { 210 | decodeAccountID(address) 211 | } catch (e) { 212 | return false 213 | } 214 | return true 215 | } 216 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "lib": [ 5 | "es2017" 6 | ], 7 | "outDir": "dist", 8 | "rootDir": "src", 9 | "module": "commonjs", 10 | "moduleResolution": "node", 11 | "noUnusedLocals": true, 12 | "noUnusedParameters": true, 13 | "removeComments": false, 14 | "preserveConstEnums": false, 15 | "suppressImplicitAnyIndexErrors": false, 16 | "sourceMap": true, 17 | "skipLibCheck": true, 18 | "declaration": true, 19 | "strict": true 20 | }, 21 | "include": [ 22 | "src/**/*.ts" 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-eslint-rules" 4 | ], 5 | "rules": { 6 | "ban": [true, ["alert"]], 7 | "no-arg": true, 8 | "no-conditional-assignment": true, 9 | "no-console": false, 10 | "no-constant-condition": true, 11 | "no-control-regex": true, 12 | "no-debugger": true, 13 | "no-duplicate-case": true, 14 | "no-empty": true, 15 | "no-empty-character-class": true, 16 | "no-eval": true, 17 | "no-ex-assign": true, 18 | "no-extra-boolean-cast": true, 19 | "no-extra-semi": true, 20 | "no-switch-case-fall-through": true, 21 | "no-inner-declarations": [true, "functions"], 22 | "no-invalid-regexp": true, 23 | "no-invalid-this": false, 24 | "no-irregular-whitespace": true, 25 | "ter-no-irregular-whitespace": true, 26 | "label-position": true, 27 | "indent": [true, "spaces", 2], 28 | "linebreak-style": [true, "unix"], 29 | "no-multi-spaces": true, 30 | "no-consecutive-blank-lines": [true, 2], 31 | "no-unused-expression": true, 32 | "no-construct": true, 33 | "no-duplicate-variable": true, 34 | "no-regex-spaces": true, 35 | "no-shadowed-variable": true, 36 | "ter-no-sparse-arrays": true, 37 | "no-trailing-whitespace": true, 38 | "no-string-throw": true, 39 | "no-unexpected-multiline": true, 40 | "no-var-keyword": true, 41 | "no-magic-numbers": false, 42 | "array-bracket-spacing": [true, "never"], 43 | "ter-arrow-body-style": false, 44 | "ter-arrow-parens": [true, "as-needed"], 45 | "ter-arrow-spacing": true, 46 | "block-spacing": true, 47 | "brace-style": [true, "1tbs", {"allowSingleLine": true}], 48 | "variable-name": false, 49 | "trailing-comma": [true, {"multiline": "never", "singleline": "never"}], 50 | "cyclomatic-complexity": [false, 11], 51 | "curly": [true, "all"], 52 | "switch-default": false, 53 | "eofline": true, 54 | "triple-equals": true, 55 | "forin": false, 56 | "handle-callback-err": true, 57 | "ter-max-len": [true, 120], 58 | "new-parens": true, 59 | "object-curly-spacing": [true, "never"], 60 | "object-literal-shorthand": false, 61 | "one-variable-per-declaration": [true, "ignore-for-loop"], 62 | "ter-prefer-arrow-callback": false, 63 | "prefer-const": true, 64 | "object-literal-key-quotes": false, 65 | "quotemark": [true, "single"], 66 | "radix": true, 67 | "semicolon": [true, "never"], 68 | "space-in-parens": [true, "never"], 69 | "comment-format": [true, "check-space"], 70 | "use-isnan": true, 71 | "valid-typeof": true 72 | } 73 | } 74 | --------------------------------------------------------------------------------