1 ! Copyright (C) 2020 John Benediktsson.
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: base64.private byte-arrays checksums checksums.sha
5 endian kernel kernel.private literals math sequences ;
9 ERROR: malformed-base58 ;
15 "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
22 : ch>base58 ( ch -- ch )
25 : base58>ch ( ch -- ch )
26 $[ alphabet alphabet-inverse ] nth
27 [ malformed-base58 ] unless* { fixnum } declare ; inline
29 :: >base58 ( seq -- base58 )
31 seq [ zero? not ] find [ drop seq length ] unless :> i
33 [ 58 /mod ch>base58 accum push ] until-zero
34 i alphabet first '[ _ accum push ] times
35 accum reverse! B{ } like ;
37 :: base58> ( base58 -- seq )
39 base58 alphabet first '[ _ = not ] find
40 [ drop base58 length ] unless :> i
41 0 base58 [ [ 58 * ] dip base58>ch + ] i each-from
42 [ 256 /mod accum push ] until-zero
43 i [ 0 accum push ] times
44 accum reverse! B{ } like ;
48 : base58-check ( base58 -- base58-check )
49 2 [ sha-256 checksum-bytes ] times ;
53 : >base58-check ( seq -- base58-check )
54 dup base58-check 4 head-slice append >base58 ;
56 : base58-check> ( base58-check -- seq )
57 base58> 4 cut* [ dup base58-check 4 head-slice ] [ assert-sequence= ] bi* ;