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.

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