github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/common/bech32/bech32_test.go (about) 1 package bech32 2 3 import ( 4 "fmt" 5 "strings" 6 "testing" 7 ) 8 9 func TestBech32(t *testing.T) { 10 tests := []struct { 11 str string 12 valid bool 13 }{ 14 {"A12UEL5L", true}, 15 {"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs", true}, 16 {"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", true}, 17 {"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", true}, 18 {"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", true}, 19 {"split1checkupstagehandshakeupstreamerranterredcaperred2y9e2w", false}, // invalid checksum 20 {"s lit1checkupstagehandshakeupstreamerranterredcaperredp8hs2p", false}, // invalid character (space) in hrp 21 {"spl" + fmt.Sprint(127) + "t1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", false}, // invalid character (DEL) in hrp 22 {"split1cheo2y9e2w", false}, // invalid character (o) in data part 23 {"split1a2y9w", false}, // too short data part 24 {"1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", false}, // empty hrp 25 {"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", false}, // too long 26 } 27 28 for _, test := range tests { 29 str := test.str 30 hrp, decoded, err := Bech32Decode(str) 31 if !test.valid { 32 // Invalid string decoding should result in error. 33 if err == nil { 34 t.Error("expected decoding to fail for "+ 35 "invalid string %v", test.str) 36 } 37 continue 38 } 39 40 // Valid string decoding should result in no error. 41 if err != nil { 42 t.Errorf("expected string to be valid bech32: %v", err) 43 } 44 45 // Check that it encodes to the same string 46 encoded, err := Bech32Encode(hrp, decoded) 47 if err != nil { 48 t.Errorf("encoding failed: %v", err) 49 } 50 51 if encoded != strings.ToLower(str) { 52 t.Errorf("expected data to encode to %v, but got %v", 53 str, encoded) 54 } 55 56 // Flip a bit in the string an make sure it is caught. 57 pos := strings.LastIndexAny(str, "1") 58 flipped := str[:pos+1] + string((str[pos+1] ^ 1)) + str[pos+2:] 59 _, _, err = Bech32Decode(flipped) 60 if err == nil { 61 t.Error("expected decoding to fail") 62 } 63 } 64 }