## Copyright (c) 2018 Status Research & Development GmbH ## Licensed under either of ## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) ## * MIT license ([LICENSE-MIT](LICENSE-MIT)) ## at your option. ## This file may not be copied, modified, or distributed except according to ## those terms. ## This module implements BASE58 encoding and decoding procedures. ## This module supports two variants of BASE58 encoding (Bitcoin and Flickr). type Base58Status* {.pure.} = enum Error, Success, Incorrect, Overrun Base58Alphabet* = object decode*: array[128, int8] encode*: array[58, uint8] BTCBase58* = object ## Type to use Bitcoin alphabet FLCBase58* = object ## Type to use Flickr alphabet Base58* = BTCBase58 ## By default we are using Bitcoin alphabet Base58C* = BTCBase58 | FLCBase58 ## Supported types Base58Error* = object of CatchableError ## Base58 specific exception type proc newAlphabet58*(s: string): Base58Alphabet = doAssert(len(s) == 58) for i in 0.. hi) or (carry != 0'u32): carry = carry + uint32(256'u32 * buffer[j]) buffer[j] = cast[byte](carry mod 58) carry = carry div 58 dec(j) hi = j inc(i) j = 0 while (j < size) and (buffer[j] == 0x00'u8): inc(j) let needed = zcount + size - j outlen = needed if len(outstr) < needed: result = Base58Status.Overrun else: for k in 0.. m: result = Base58Status.Overrun return break inc(m) dec(outlen) if m < binsz: moveMem(addr outbytes[zcount], addr outbytes[binsz - outlen], outlen) outlen += zcount result = Base58Status.Success proc decode*(btype: typedesc[Base58C], instr: string): seq[byte] = ## Decode BASE58 string ``instr`` and return sequence of bytes as result. if len(instr) > 0: var size = len(instr) + 4 result = newSeq[byte](size) if btype.decode(instr, result, size) == Base58Status.Success: result.setLen(size) else: raise newException(Base58Error, "Incorrect base58 string")