From 2c0d52f4b5a70a798bea3d2c7a203d9664eb1240 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 20 Jun 2017 16:52:04 +0200 Subject: [PATCH] Add typo detector test, fix panics --- keys/wordcodec.go | 8 ++++++++ keys/wordcodec_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/keys/wordcodec.go b/keys/wordcodec.go index c69f7ae1d..5ac32f812 100644 --- a/keys/wordcodec.go +++ b/keys/wordcodec.go @@ -122,6 +122,11 @@ func (c WordCodec) BytesToWords(raw []byte) (words []string, err error) { func (c WordCodec) WordsToBytes(words []string) ([]byte, error) { l := len(words) + + if l == 0 { + return nil, errors.New("Didn't provide any words") + } + n2048 := big.NewInt(2048) nData := big.NewInt(0) // since we output words based on the remainder, the first word has the lowest @@ -143,6 +148,9 @@ func (c WordCodec) WordsToBytes(words []string) ([]byte, error) { // copy into the container we have with the expected size outLen, flex := bytelenFromWords(len(words)) toCheck := make([]byte, outLen) + if len(dataBytes) > outLen { + return nil, errors.New("Invalid data, could not have been generated by this codec") + } copy(toCheck[outLen-len(dataBytes):], dataBytes) // validate the checksum... diff --git a/keys/wordcodec_test.go b/keys/wordcodec_test.go index 40ac24f42..b9496a0ef 100644 --- a/keys/wordcodec_test.go +++ b/keys/wordcodec_test.go @@ -130,6 +130,52 @@ func TestCheckInvalidLists(t *testing.T) { } +func getRandWord(c WordCodec) string { + idx := cmn.RandInt() % BankSize + return c.words[idx] +} + +func getDiffWord(c WordCodec, not string) string { + w := getRandWord(c) + if w == not { + w = getRandWord(c) + } + return w +} + func TestCheckTypoDetection(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + banks := []string{"english"} + + for _, bank := range banks { + codec, err := LoadCodec(bank) + require.Nil(err, "%s: %+v", bank, err) + for i := 0; i < 10; i++ { + numBytes := cmn.RandInt()%60 + 1 + data := cmn.RandBytes(numBytes) + + words, err := codec.BytesToWords(data) + assert.Nil(err, "%s: %+v", bank, err) + good, err := codec.WordsToBytes(words) + assert.Nil(err, "%s: %+v", bank, err) + assert.Equal(data, good, bank) + + // now try some tweaks... + cut := words[1:] + _, err = codec.WordsToBytes(cut) + assert.NotNil(err, "%s: %s", bank, words) + + // swap a word within the bank, should fails + words[3] = getDiffWord(codec, words[3]) + _, err = codec.WordsToBytes(words) + assert.NotNil(err, "%s: %s", bank, words) + + // put a random word here, must fail + words[3] = cmn.RandStr(10) + _, err = codec.WordsToBytes(words) + assert.NotNil(err, "%s: %s", bank, words) + } + } }