precompute.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2015 The btcsuite developers
  2. // Use of this source code is governed by an ISC
  3. // license that can be found in the LICENSE file.
  4. package btcec
  5. import (
  6. "compress/zlib"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "io/ioutil"
  10. "strings"
  11. )
  12. //go:generate go run -tags gensecp256k1 genprecomps.go
  13. // loadS256BytePoints decompresses and deserializes the pre-computed byte points
  14. // used to accelerate scalar base multiplication for the secp256k1 curve. This
  15. // approach is used since it allows the compile to use significantly less ram
  16. // and be performed much faster than it is with hard-coding the final in-memory
  17. // data structure. At the same time, it is quite fast to generate the in-memory
  18. // data structure at init time with this approach versus computing the table.
  19. func loadS256BytePoints() error {
  20. // There will be no byte points to load when generating them.
  21. bp := secp256k1BytePoints
  22. if len(bp) == 0 {
  23. return nil
  24. }
  25. // Decompress the pre-computed table used to accelerate scalar base
  26. // multiplication.
  27. decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(bp))
  28. r, err := zlib.NewReader(decoder)
  29. if err != nil {
  30. return err
  31. }
  32. serialized, err := ioutil.ReadAll(r)
  33. if err != nil {
  34. return err
  35. }
  36. // Deserialize the precomputed byte points and set the curve to them.
  37. offset := 0
  38. var bytePoints [32][256][3]fieldVal
  39. for byteNum := 0; byteNum < 32; byteNum++ {
  40. // All points in this window.
  41. for i := 0; i < 256; i++ {
  42. px := &bytePoints[byteNum][i][0]
  43. py := &bytePoints[byteNum][i][1]
  44. pz := &bytePoints[byteNum][i][2]
  45. for i := 0; i < 10; i++ {
  46. px.n[i] = binary.LittleEndian.Uint32(serialized[offset:])
  47. offset += 4
  48. }
  49. for i := 0; i < 10; i++ {
  50. py.n[i] = binary.LittleEndian.Uint32(serialized[offset:])
  51. offset += 4
  52. }
  53. for i := 0; i < 10; i++ {
  54. pz.n[i] = binary.LittleEndian.Uint32(serialized[offset:])
  55. offset += 4
  56. }
  57. }
  58. }
  59. secp256k1.bytePoints = &bytePoints
  60. return nil
  61. }