UNPKG

@secux/utility

Version:

SecuX Hardware Wallet internal tools for SDK

18 lines (15 loc) 2.7 kB
"use strict"; /*! Copyright 2022 SecuX Technology Inc Copyright Chen Wei-En Copyright Wu Tsung-Yu 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. */Object.defineProperty(exports,"__esModule",{value:!0}),exports.HARDENED_OFFSET=exports.splitPath=exports.decodePathBuffer=exports.buildPathBuffer=void 0;function splitPath(path){const elements=path.split("/"),pathLen=elements.length;if(pathLen<2||pathLen>6)throw Error("Invalid Path, only support 1 to 5 depth path");const pathProps={};return pathProps.pathNum=pathLen-1,elements.forEach(((element,index)=>{if(0===index)return;const props={},isHardened=element.length>1&&"'"===element[element.length-1];switch(props.value=isHardened?parseInt(element.slice(0,-1),10):parseInt(element,10),props.isHardened=isHardened,props.depth=index,index){case 1:pathProps.purpose=props;break;case 2:pathProps.coinType=props;break;case 3:pathProps.accountId=props;break;case 4:pathProps.change=props;break;case 5:pathProps.addressIndex=props}})),pathProps}exports.HARDENED_OFFSET=2147483648,exports.buildPathBuffer=function(path,num){const getHardenedValue=pathLevel=>{if(pathLevel&&pathLevel.isHardened)return pathLevel.value+2147483648;if(pathLevel&&!pathLevel.isHardened)return pathLevel.value;throw Error("Build path error")},pathProps=splitPath(path);let pathNum=num&&num>=1&&num<6?num:pathProps.pathNum;const buf=Buffer.alloc(4*pathNum),{purpose,coinType,accountId,change,addressIndex}=pathProps;for(let i=0;i<pathNum;i++)switch(i){case 0:buf.writeUInt32LE(getHardenedValue(purpose),4*i);break;case 1:buf.writeUInt32LE(getHardenedValue(coinType),4*i);break;case 2:buf.writeUInt32LE(getHardenedValue(accountId),4*i);break;case 3:buf.writeUInt32LE(getHardenedValue(change),4*i);break;case 4:buf.writeUInt32LE(getHardenedValue(addressIndex),4*i)}return{pathNum,pathBuffer:buf}},exports.decodePathBuffer=function(data){if(data.length%4!=0)throw Error("ArgumentError: each element of path should be 4 bytes");if(data.length<=0||data.length>20)throw Error("ArgumentError: invalid Path, only support 1 to 5 depth path");let path="m";for(let i=0;i<data.length;i+=4){const e=data.readUInt32LE(i);path=e>=2147483648?`${path}/${e-2147483648}'`:`${path}/${e}`}return path},exports.splitPath=splitPath;