You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
4.8 KiB

  1. package keys
  2. import (
  3. "math/big"
  4. "strings"
  5. "github.com/pkg/errors"
  6. "github.com/tendermint/go-crypto/keys/wordlist"
  7. )
  8. const BankSize = 2048
  9. // TODO: add error-checking codecs for invalid phrases
  10. type Codec interface {
  11. BytesToWords([]byte) ([]string, error)
  12. WordsToBytes([]string) ([]byte, error)
  13. }
  14. type WordCodec struct {
  15. words []string
  16. bytes map[string]int
  17. check ECC
  18. }
  19. var _ Codec = &WordCodec{}
  20. func NewCodec(words []string) (codec *WordCodec, err error) {
  21. if len(words) != BankSize {
  22. return codec, errors.Errorf("Bank must have %d words, found %d", BankSize, len(words))
  23. }
  24. res := &WordCodec{
  25. words: words,
  26. // TODO: configure this outside???
  27. check: NewIEEECRC32(),
  28. }
  29. return res, nil
  30. }
  31. // LoadCodec loads a pre-compiled language file
  32. func LoadCodec(bank string) (codec *WordCodec, err error) {
  33. words, err := loadBank(bank)
  34. if err != nil {
  35. return codec, err
  36. }
  37. return NewCodec(words)
  38. }
  39. // MustLoadCodec panics if word bank is missing, only for tests
  40. func MustLoadCodec(bank string) *WordCodec {
  41. codec, err := LoadCodec(bank)
  42. if err != nil {
  43. panic(err)
  44. }
  45. return codec
  46. }
  47. // loadBank opens a wordlist file and returns all words inside
  48. func loadBank(bank string) ([]string, error) {
  49. filename := "keys/wordlist/" + bank + ".txt"
  50. words, err := wordlist.Asset(filename)
  51. if err != nil {
  52. return nil, err
  53. }
  54. wordsAll := strings.Split(strings.TrimSpace(string(words)), "\n")
  55. return wordsAll, nil
  56. }
  57. // // TODO: read from go-bind assets
  58. // func getData(filename string) (string, error) {
  59. // f, err := os.Open(filename)
  60. // if err != nil {
  61. // return "", errors.WithStack(err)
  62. // }
  63. // defer f.Close()
  64. // data, err := ioutil.ReadAll(f)
  65. // if err != nil {
  66. // return "", errors.WithStack(err)
  67. // }
  68. // return string(data), nil
  69. // }
  70. // given this many bytes, we will produce this many words
  71. func wordlenFromBytes(numBytes int) int {
  72. // 2048 words per bank, which is 2^11.
  73. // 8 bits per byte, and we add +10 so it rounds up
  74. return (8*numBytes + 10) / 11
  75. }
  76. // given this many words, we will produce this many bytes.
  77. // sometimes there are two possibilities.
  78. // if maybeShorter is true, then represents len OR len-1 bytes
  79. func bytelenFromWords(numWords int) (length int, maybeShorter bool) {
  80. // calculate the max number of complete bytes we could store in this word
  81. length = 11 * numWords / 8
  82. // if one less byte would also generate this length, set maybeShorter
  83. if wordlenFromBytes(length-1) == numWords {
  84. maybeShorter = true
  85. }
  86. return
  87. }
  88. // TODO: add checksum
  89. func (c *WordCodec) BytesToWords(raw []byte) (words []string, err error) {
  90. // always add a checksum to the data
  91. data := c.check.AddECC(raw)
  92. numWords := wordlenFromBytes(len(data))
  93. n2048 := big.NewInt(2048)
  94. nData := big.NewInt(0).SetBytes(data)
  95. nRem := big.NewInt(0)
  96. // Alternative, use condition "nData.BitLen() > 0"
  97. // to allow for shorter words when data has leading 0's
  98. for i := 0; i < numWords; i++ {
  99. nData.DivMod(nData, n2048, nRem)
  100. rem := nRem.Int64()
  101. w := c.words[rem]
  102. // double-check bank on generation...
  103. _, err := c.GetIndex(w)
  104. if err != nil {
  105. return nil, err
  106. }
  107. words = append(words, w)
  108. }
  109. return words, nil
  110. }
  111. func (c *WordCodec) WordsToBytes(words []string) ([]byte, error) {
  112. l := len(words)
  113. if l == 0 {
  114. return nil, errors.New("Didn't provide any words")
  115. }
  116. n2048 := big.NewInt(2048)
  117. nData := big.NewInt(0)
  118. // since we output words based on the remainder, the first word has the lowest
  119. // value... we must load them in reverse order
  120. for i := 1; i <= l; i++ {
  121. rem, err := c.GetIndex(words[l-i])
  122. if err != nil {
  123. return nil, err
  124. }
  125. nRem := big.NewInt(int64(rem))
  126. nData.Mul(nData, n2048)
  127. nData.Add(nData, nRem)
  128. }
  129. // we copy into a slice of the expected size, so it is not shorter if there
  130. // are lots of leading 0s
  131. dataBytes := nData.Bytes()
  132. // copy into the container we have with the expected size
  133. outLen, flex := bytelenFromWords(len(words))
  134. toCheck := make([]byte, outLen)
  135. if len(dataBytes) > outLen {
  136. return nil, errors.New("Invalid data, could not have been generated by this codec")
  137. }
  138. copy(toCheck[outLen-len(dataBytes):], dataBytes)
  139. // validate the checksum...
  140. output, err := c.check.CheckECC(toCheck)
  141. if flex && err != nil {
  142. // if flex, try again one shorter....
  143. toCheck = toCheck[1:]
  144. output, err = c.check.CheckECC(toCheck)
  145. }
  146. return output, err
  147. }
  148. // GetIndex finds the index of the words to create bytes
  149. // Generates a map the first time it is loaded, to avoid needless
  150. // computation when list is not used.
  151. func (c *WordCodec) GetIndex(word string) (int, error) {
  152. // generate the first time
  153. if c.bytes == nil {
  154. b := map[string]int{}
  155. for i, w := range c.words {
  156. if _, ok := b[w]; ok {
  157. return -1, errors.Errorf("Duplicate word in list: %s", w)
  158. }
  159. b[w] = i
  160. }
  161. c.bytes = b
  162. }
  163. // get the index, or an error
  164. rem, ok := c.bytes[word]
  165. if !ok {
  166. return -1, errors.Errorf("Unrecognized word: %s", word)
  167. }
  168. return rem, nil
  169. }