import Sodium from 'react-native-sodium' ; import { sha256 } from 'js-sha256' ; import bs58 from 'bs58' ; import { NetType } from './NetType' ; import { KeyType } from './KeyType' ; export const randomBytes = async ( n ) : Promise < Buffer > => { const bytes = await Sodium . randombytes_buf ( n ) ; return Buffer . from ( bytes , 'base64' ) ; } ; export const lpad = ( str , padString , length ) => { let strOut = str ; while ( strOut . length < length ) strOut = padString + strOut ; return strOut ; } ; export const bytesToBinary = ( bytes ) => bytes . map ( ( x ) => lpad ( x . toString ( 2 ) , '0' , 8 ) ) . join ( '' ) ; export const binaryToByte = ( bin ) => parseInt ( bin , 2 ) ; export const deriveChecksumBits = ( entropyBuffer ) => { const ENT = entropyBuffer . length * 8 ; const CS = ENT / 32 ; const hash = sha256 . digest ( entropyBuffer ) ; return bytesToBinary ( Array . from ( hash ) ) . slice ( 0 , CS ) ; } ; export const bs58CheckEncode = ( version , binary ) : string => { const vPayload = Buffer . concat ( [ Buffer . from ( [ version ] ) , binary , ] ) ; const checksum = sha256 ( Buffer . from ( sha256 ( vPayload ) , 'hex' ) ) ; const checksumBytes = Buffer . alloc ( 4 , checksum , 'hex' ) ; const result = Buffer . concat ( [ vPayload , checksumBytes , ] ) ; return bs58 . encode ( result ) ; } ; export const bs58ToBin = ( bs58Address ) : Buffer => { const bin = bs58 . decode ( bs58Address ) ; const vPayload = bin . slice ( 0 , - 4 ) ; const payload = bin . slice ( 1 , - 4 ) ; const checksum = bin . slice ( - 4 ) ; const checksumVerify = sha256 ( Buffer . from ( sha256 ( vPayload ) , 'hex' ) ) ; const checksumVerifyBytes = Buffer . alloc ( 4 , checksumVerify , 'hex' ) ; if ( ! checksumVerifyBytes . equals ( checksum ) ) { throw new Error ( 'invalid checksum' ) ; } return payload ; } ; export const byteToNetType = ( byte ) : NetType => byte & 0xf0 ; export const byteToKeyType = ( byte ) : KeyType => byte & 0x0f ; export const bs58NetType = ( bs58Address ) : NetType => { const bin = bs58ToBin ( bs58Address ) ; const byte = Buffer . from ( bin ) . slice ( 0 , 1 ) [ 0 ] ; return byteToNetType ( byte ) ; } ; export const bs58KeyType = ( bs58Address ) : KeyType => { const bin = bs58ToBin ( bs58Address ) ; const byte = Buffer . from ( bin ) . slice ( 0 , 1 ) [ 0 ] ; return byteToKeyType ( byte ) ; } ; export const bs58Version = ( bs58Address ) : number => { const bin = bs58 . decode ( bs58Address ) ; const version = bin . slice ( 0 , 1 ) [ 0 ] ; return version ; } ; export const bs58PublicKey = ( bs58Address ) : Buffer => { const bin = bs58ToBin ( bs58Address ) ; const publicKey = Buffer . from ( bin ) . slice ( 1 ) ; return publicKey ; } ;