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.

1328 lines
29 KiB

  1. package parsers
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "math/big"
  11. "os"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare"
  16. "github.com/iden3/go-circom-prover-verifier/types"
  17. )
  18. // PkString is the equivalent to the Pk struct in string representation, containing the ProvingKey
  19. type PkString struct {
  20. A [][]string `json:"A"`
  21. B2 [][][]string `json:"B2"`
  22. B1 [][]string `json:"B1"`
  23. C [][]string `json:"C"`
  24. NVars int `json:"nVars"`
  25. NPublic int `json:"nPublic"`
  26. VkAlpha1 []string `json:"vk_alfa_1"`
  27. VkDelta1 []string `json:"vk_delta_1"`
  28. VkBeta1 []string `json:"vk_beta_1"`
  29. VkBeta2 [][]string `json:"vk_beta_2"`
  30. VkDelta2 [][]string `json:"vk_delta_2"`
  31. HExps [][]string `json:"hExps"`
  32. DomainSize int `json:"domainSize"`
  33. PolsA []map[string]string `json:"polsA"`
  34. PolsB []map[string]string `json:"polsB"`
  35. }
  36. // WitnessString contains the Witness in string representation
  37. type WitnessString []string
  38. // ProofString is the equivalent to the Proof struct in string representation
  39. type ProofString struct {
  40. A []string `json:"pi_a"`
  41. B [][]string `json:"pi_b"`
  42. C []string `json:"pi_c"`
  43. Protocol string `json:"protocol"`
  44. }
  45. // VkString is the Verification Key data structure in string format (from json)
  46. type VkString struct {
  47. Alpha []string `json:"vk_alfa_1"`
  48. Beta [][]string `json:"vk_beta_2"`
  49. Gamma [][]string `json:"vk_gamma_2"`
  50. Delta [][]string `json:"vk_delta_2"`
  51. IC [][]string `json:"IC"`
  52. }
  53. // ParseWitness parses the json []byte data into the Witness struct
  54. func ParseWitness(wJson []byte) (types.Witness, error) {
  55. var ws WitnessString
  56. err := json.Unmarshal(wJson, &ws)
  57. if err != nil {
  58. return nil, err
  59. }
  60. var w types.Witness
  61. for i := 0; i < len(ws); i++ {
  62. bi, err := stringToBigInt(ws[i])
  63. if err != nil {
  64. return nil, err
  65. }
  66. w = append(w, bi)
  67. }
  68. return w, nil
  69. }
  70. // ParsePk parses the json []byte data into the Pk struct
  71. func ParsePk(pkJson []byte) (*types.Pk, error) {
  72. var pkStr PkString
  73. err := json.Unmarshal(pkJson, &pkStr)
  74. if err != nil {
  75. return nil, err
  76. }
  77. pk, err := pkStringToPk(pkStr)
  78. return pk, err
  79. }
  80. func pkStringToPk(ps PkString) (*types.Pk, error) {
  81. var p types.Pk
  82. var err error
  83. p.A, err = arrayStringToG1(ps.A)
  84. if err != nil {
  85. return nil, err
  86. }
  87. p.B2, err = arrayStringToG2(ps.B2)
  88. if err != nil {
  89. return nil, err
  90. }
  91. p.B1, err = arrayStringToG1(ps.B1)
  92. if err != nil {
  93. return nil, err
  94. }
  95. p.C, err = arrayStringToG1(ps.C)
  96. if err != nil {
  97. return nil, err
  98. }
  99. p.NVars = ps.NVars
  100. p.NPublic = ps.NPublic
  101. p.VkAlpha1, err = stringToG1(ps.VkAlpha1)
  102. if err != nil {
  103. return nil, err
  104. }
  105. p.VkDelta1, err = stringToG1(ps.VkDelta1)
  106. if err != nil {
  107. return nil, err
  108. }
  109. p.VkBeta1, err = stringToG1(ps.VkBeta1)
  110. if err != nil {
  111. return nil, err
  112. }
  113. p.VkBeta2, err = stringToG2(ps.VkBeta2)
  114. if err != nil {
  115. return nil, err
  116. }
  117. p.VkDelta2, err = stringToG2(ps.VkDelta2)
  118. if err != nil {
  119. return nil, err
  120. }
  121. p.HExps, err = arrayStringToG1(ps.HExps)
  122. if err != nil {
  123. return nil, err
  124. }
  125. p.DomainSize = ps.DomainSize
  126. p.PolsA, err = polsStringToBigInt(ps.PolsA)
  127. if err != nil {
  128. return nil, err
  129. }
  130. p.PolsB, err = polsStringToBigInt(ps.PolsB)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return &p, nil
  135. }
  136. func proofStringToProof(pr ProofString) (*types.Proof, error) {
  137. var p types.Proof
  138. var err error
  139. p.A, err = stringToG1(pr.A)
  140. if err != nil {
  141. return nil, err
  142. }
  143. p.B, err = stringToG2(pr.B)
  144. if err != nil {
  145. return nil, err
  146. }
  147. p.C, err = stringToG1(pr.C)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return &p, nil
  152. }
  153. // ParseProof takes a json []byte and outputs the *Proof struct
  154. func ParseProof(pj []byte) (*types.Proof, error) {
  155. var pr ProofString
  156. err := json.Unmarshal(pj, &pr)
  157. if err != nil {
  158. return nil, err
  159. }
  160. p, err := proofStringToProof(pr)
  161. return p, err
  162. }
  163. // ParsePublicSignals takes a json []byte and outputs the []*big.Int struct
  164. func ParsePublicSignals(pj []byte) ([]*big.Int, error) {
  165. var pr []string
  166. err := json.Unmarshal(pj, &pr)
  167. if err != nil {
  168. return nil, err
  169. }
  170. var public []*big.Int
  171. for _, s := range pr {
  172. sb, err := stringToBigInt(s)
  173. if err != nil {
  174. return nil, err
  175. }
  176. public = append(public, sb)
  177. }
  178. return public, nil
  179. }
  180. // ParseVk takes a json []byte and outputs the *Vk struct
  181. func ParseVk(vj []byte) (*types.Vk, error) {
  182. var vr VkString
  183. err := json.Unmarshal(vj, &vr)
  184. if err != nil {
  185. return nil, err
  186. }
  187. v, err := vkStringToVk(vr)
  188. return v, err
  189. }
  190. func vkStringToVk(vr VkString) (*types.Vk, error) {
  191. var v types.Vk
  192. var err error
  193. v.Alpha, err = stringToG1(vr.Alpha)
  194. if err != nil {
  195. return nil, err
  196. }
  197. v.Beta, err = stringToG2(vr.Beta)
  198. if err != nil {
  199. return nil, err
  200. }
  201. v.Gamma, err = stringToG2(vr.Gamma)
  202. if err != nil {
  203. return nil, err
  204. }
  205. v.Delta, err = stringToG2(vr.Delta)
  206. if err != nil {
  207. return nil, err
  208. }
  209. for i := 0; i < len(vr.IC); i++ {
  210. p, err := stringToG1(vr.IC[i])
  211. if err != nil {
  212. return nil, err
  213. }
  214. v.IC = append(v.IC, p)
  215. }
  216. return &v, nil
  217. }
  218. // polsStringToBigInt is for taking string polynomials and converting it to *big.Int polynomials
  219. func polsStringToBigInt(s []map[string]string) ([]map[int]*big.Int, error) {
  220. var o []map[int]*big.Int
  221. for i := 0; i < len(s); i++ {
  222. // var oi map[int]*big.Int
  223. oi := make(map[int]*big.Int)
  224. for j, v := range s[i] {
  225. si, err := stringToBigInt(v)
  226. if err != nil {
  227. return o, err
  228. }
  229. // oi = append(oi, si)
  230. jInt, err := strconv.Atoi(j)
  231. if err != nil {
  232. return o, err
  233. }
  234. oi[jInt] = si
  235. }
  236. o = append(o, oi)
  237. }
  238. return o, nil
  239. }
  240. // ArrayBigIntToString converts an []*big.Int into []string, used to output the Public Signals
  241. func ArrayBigIntToString(bi []*big.Int) []string {
  242. var s []string
  243. for i := 0; i < len(bi); i++ {
  244. s = append(s, bi[i].String())
  245. }
  246. return s
  247. }
  248. func arrayStringToBigInt(s []string) ([]*big.Int, error) {
  249. var o []*big.Int
  250. for i := 0; i < len(s); i++ {
  251. si, err := stringToBigInt(s[i])
  252. if err != nil {
  253. return o, nil
  254. }
  255. o = append(o, si)
  256. }
  257. return o, nil
  258. }
  259. func stringToBigInt(s string) (*big.Int, error) {
  260. base := 10
  261. if bytes.HasPrefix([]byte(s), []byte("0x")) {
  262. base = 16
  263. s = strings.TrimPrefix(s, "0x")
  264. }
  265. n, ok := new(big.Int).SetString(s, base)
  266. if !ok {
  267. return nil, fmt.Errorf("Can not parse string to *big.Int: %s", s)
  268. }
  269. return n, nil
  270. }
  271. func addPadding32(b []byte) []byte {
  272. if len(b) != 32 {
  273. b = addZPadding(b)
  274. }
  275. return b
  276. }
  277. func addZPadding(b []byte) []byte {
  278. var z [32]byte
  279. var r []byte
  280. r = append(r, z[len(b):]...) // add padding on the left
  281. r = append(r, b...)
  282. return r[:32]
  283. }
  284. func stringToBytes(s string) ([]byte, error) {
  285. if s == "1" {
  286. s = "0"
  287. }
  288. bi, ok := new(big.Int).SetString(s, 10)
  289. if !ok {
  290. return nil, fmt.Errorf("error parsing bigint stringToBytes")
  291. }
  292. b := bi.Bytes()
  293. if len(b) != 32 {
  294. b = addZPadding(b)
  295. }
  296. return b, nil
  297. }
  298. func arrayStringToG1(h [][]string) ([]*bn256.G1, error) {
  299. var o []*bn256.G1
  300. for i := 0; i < len(h); i++ {
  301. hi, err := stringToG1(h[i])
  302. if err != nil {
  303. return o, err
  304. }
  305. o = append(o, hi)
  306. }
  307. return o, nil
  308. }
  309. func arrayStringToG2(h [][][]string) ([]*bn256.G2, error) {
  310. var o []*bn256.G2
  311. for i := 0; i < len(h); i++ {
  312. hi, err := stringToG2(h[i])
  313. if err != nil {
  314. return o, err
  315. }
  316. o = append(o, hi)
  317. }
  318. return o, nil
  319. }
  320. func stringToG1(h []string) (*bn256.G1, error) {
  321. if len(h) <= 2 {
  322. return nil, fmt.Errorf("not enought data for stringToG1")
  323. }
  324. h = h[:2]
  325. hexa := false
  326. if len(h[0]) > 1 {
  327. if "0x" == h[0][:2] {
  328. hexa = true
  329. }
  330. }
  331. in := ""
  332. var b []byte
  333. var err error
  334. if hexa {
  335. for i := range h {
  336. in += strings.TrimPrefix(h[i], "0x")
  337. }
  338. b, err = hex.DecodeString(in)
  339. if err != nil {
  340. return nil, err
  341. }
  342. } else {
  343. // TODO TMP
  344. // TODO use stringToBytes()
  345. if h[0] == "1" {
  346. h[0] = "0"
  347. }
  348. if h[1] == "1" {
  349. h[1] = "0"
  350. }
  351. bi0, ok := new(big.Int).SetString(h[0], 10)
  352. if !ok {
  353. return nil, fmt.Errorf("error parsing stringToG1")
  354. }
  355. bi1, ok := new(big.Int).SetString(h[1], 10)
  356. if !ok {
  357. return nil, fmt.Errorf("error parsing stringToG1")
  358. }
  359. b0 := bi0.Bytes()
  360. b1 := bi1.Bytes()
  361. if len(b0) != 32 {
  362. b0 = addZPadding(b0)
  363. }
  364. if len(b1) != 32 {
  365. b1 = addZPadding(b1)
  366. }
  367. b = append(b, b0...)
  368. b = append(b, b1...)
  369. }
  370. p := new(bn256.G1)
  371. _, err = p.Unmarshal(b)
  372. return p, err
  373. }
  374. func stringToG2(h [][]string) (*bn256.G2, error) {
  375. if len(h) <= 2 {
  376. return nil, fmt.Errorf("not enought data for stringToG2")
  377. }
  378. h = h[:2]
  379. hexa := false
  380. if len(h[0][0]) > 1 {
  381. if "0x" == h[0][0][:2] {
  382. hexa = true
  383. }
  384. }
  385. in := ""
  386. var b []byte
  387. var err error
  388. if hexa {
  389. for i := 0; i < len(h); i++ {
  390. for j := 0; j < len(h[i]); j++ {
  391. in += strings.TrimPrefix(h[i][j], "0x")
  392. }
  393. }
  394. b, err = hex.DecodeString(in)
  395. if err != nil {
  396. return nil, err
  397. }
  398. } else {
  399. // TODO TMP
  400. bH, err := stringToBytes(h[0][1])
  401. if err != nil {
  402. return nil, err
  403. }
  404. b = append(b, bH...)
  405. bH, err = stringToBytes(h[0][0])
  406. if err != nil {
  407. return nil, err
  408. }
  409. b = append(b, bH...)
  410. bH, err = stringToBytes(h[1][1])
  411. if err != nil {
  412. return nil, err
  413. }
  414. b = append(b, bH...)
  415. bH, err = stringToBytes(h[1][0])
  416. if err != nil {
  417. return nil, err
  418. }
  419. b = append(b, bH...)
  420. }
  421. p := new(bn256.G2)
  422. _, err = p.Unmarshal(b)
  423. return p, err
  424. }
  425. // ProofStringToSmartContractFormat converts the ProofString to a ProofString in the SmartContract format in a ProofString structure
  426. func ProofStringToSmartContractFormat(s ProofString) ProofString {
  427. var rs ProofString
  428. rs.A = make([]string, 2)
  429. rs.B = make([][]string, 2)
  430. rs.B[0] = make([]string, 2)
  431. rs.B[1] = make([]string, 2)
  432. rs.C = make([]string, 2)
  433. rs.A[0] = s.A[0]
  434. rs.A[1] = s.A[1]
  435. rs.B[0][0] = s.B[0][1]
  436. rs.B[0][1] = s.B[0][0]
  437. rs.B[1][0] = s.B[1][1]
  438. rs.B[1][1] = s.B[1][0]
  439. rs.C[0] = s.C[0]
  440. rs.C[1] = s.C[1]
  441. rs.Protocol = s.Protocol
  442. return rs
  443. }
  444. // ProofToSmartContractFormat converts the *types.Proof to a ProofString in the SmartContract format in a ProofString structure
  445. func ProofToSmartContractFormat(p *types.Proof) ProofString {
  446. s := ProofToString(p)
  447. return ProofStringToSmartContractFormat(s)
  448. }
  449. // ProofToString converts the Proof to ProofString
  450. func ProofToString(p *types.Proof) ProofString {
  451. var ps ProofString
  452. ps.A = make([]string, 3)
  453. ps.B = make([][]string, 3)
  454. ps.B[0] = make([]string, 2)
  455. ps.B[1] = make([]string, 2)
  456. ps.B[2] = make([]string, 2)
  457. ps.C = make([]string, 3)
  458. a := p.A.Marshal()
  459. ps.A[0] = new(big.Int).SetBytes(a[:32]).String()
  460. ps.A[1] = new(big.Int).SetBytes(a[32:64]).String()
  461. ps.A[2] = "1"
  462. b := p.B.Marshal()
  463. ps.B[0][1] = new(big.Int).SetBytes(b[:32]).String()
  464. ps.B[0][0] = new(big.Int).SetBytes(b[32:64]).String()
  465. ps.B[1][1] = new(big.Int).SetBytes(b[64:96]).String()
  466. ps.B[1][0] = new(big.Int).SetBytes(b[96:128]).String()
  467. ps.B[2][0] = "1"
  468. ps.B[2][1] = "0"
  469. c := p.C.Marshal()
  470. ps.C[0] = new(big.Int).SetBytes(c[:32]).String()
  471. ps.C[1] = new(big.Int).SetBytes(c[32:64]).String()
  472. ps.C[2] = "1"
  473. ps.Protocol = "groth"
  474. return ps
  475. }
  476. // ProofToJson outputs the Proof i Json format
  477. func ProofToJson(p *types.Proof) ([]byte, error) {
  478. ps := ProofToString(p)
  479. return json.Marshal(ps)
  480. }
  481. // ProofToHex converts the Proof to ProofString with hexadecimal strings
  482. func ProofToHex(p *types.Proof) ProofString {
  483. var ps ProofString
  484. ps.A = make([]string, 3)
  485. ps.B = make([][]string, 3)
  486. ps.B[0] = make([]string, 2)
  487. ps.B[1] = make([]string, 2)
  488. ps.B[2] = make([]string, 2)
  489. ps.C = make([]string, 3)
  490. a := p.A.Marshal()
  491. ps.A[0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(a[:32]).Bytes())
  492. ps.A[1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(a[32:64]).Bytes())
  493. ps.A[2] = "1"
  494. b := p.B.Marshal()
  495. ps.B[0][1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[:32]).Bytes())
  496. ps.B[0][0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[32:64]).Bytes())
  497. ps.B[1][1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[64:96]).Bytes())
  498. ps.B[1][0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[96:128]).Bytes())
  499. ps.B[2][0] = "1"
  500. ps.B[2][1] = "0"
  501. c := p.C.Marshal()
  502. ps.C[0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(c[:32]).Bytes())
  503. ps.C[1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(c[32:64]).Bytes())
  504. ps.C[2] = "1"
  505. ps.Protocol = "groth"
  506. return ps
  507. }
  508. // ProofToJsonHex outputs the Proof i Json format with hexadecimal strings
  509. func ProofToJsonHex(p *types.Proof) ([]byte, error) {
  510. ps := ProofToHex(p)
  511. return json.Marshal(ps)
  512. }
  513. // ParseWitnessBin parses binary file representation of the Witness into the Witness struct
  514. func ParseWitnessBin(f *os.File) (types.Witness, error) {
  515. var w types.Witness
  516. r := bufio.NewReader(f)
  517. for {
  518. b := make([]byte, 32)
  519. n, err := r.Read(b)
  520. if err == io.EOF {
  521. return w, nil
  522. } else if err != nil {
  523. return nil, err
  524. }
  525. if n != 32 {
  526. return nil, fmt.Errorf("error on value format, expected 32 bytes, got %v", n)
  527. }
  528. w = append(w, new(big.Int).SetBytes(swapEndianness(b[0:32])))
  529. }
  530. }
  531. // swapEndianness swaps the order of the bytes in the slice.
  532. func swapEndianness(b []byte) []byte {
  533. o := make([]byte, len(b))
  534. for i := range b {
  535. o[len(b)-1-i] = b[i]
  536. }
  537. return o
  538. }
  539. func readNBytes(r io.Reader, n int) ([]byte, error) {
  540. b := make([]byte, n)
  541. _, err := io.ReadFull(r, b)
  542. if err != nil {
  543. return b, err
  544. }
  545. return b, nil
  546. }
  547. // ParsePkBin parses binary file representation of the ProvingKey into the ProvingKey struct
  548. func ParsePkBin(f *os.File) (*types.Pk, error) {
  549. o := 0
  550. var pk types.Pk
  551. r := bufio.NewReader(f)
  552. b, err := readNBytes(r, 12)
  553. if err != nil {
  554. return nil, err
  555. }
  556. pk.NVars = int(binary.LittleEndian.Uint32(b[:4]))
  557. pk.NPublic = int(binary.LittleEndian.Uint32(b[4:8]))
  558. pk.DomainSize = int(binary.LittleEndian.Uint32(b[8:12]))
  559. o += 12
  560. b, err = readNBytes(r, 8)
  561. if err != nil {
  562. return nil, err
  563. }
  564. pPolsA := int(binary.LittleEndian.Uint32(b[:4]))
  565. pPolsB := int(binary.LittleEndian.Uint32(b[4:8]))
  566. o += 8
  567. b, err = readNBytes(r, 20)
  568. if err != nil {
  569. return nil, err
  570. }
  571. pPointsA := int(binary.LittleEndian.Uint32(b[:4]))
  572. pPointsB1 := int(binary.LittleEndian.Uint32(b[4:8]))
  573. pPointsB2 := int(binary.LittleEndian.Uint32(b[8:12]))
  574. pPointsC := int(binary.LittleEndian.Uint32(b[12:16]))
  575. pPointsHExps := int(binary.LittleEndian.Uint32(b[16:20]))
  576. o += 20
  577. b, err = readNBytes(r, 64)
  578. if err != nil {
  579. return nil, err
  580. }
  581. pk.VkAlpha1 = new(bn256.G1)
  582. _, err = pk.VkAlpha1.Unmarshal(fromMont1Q(b))
  583. if err != nil {
  584. return nil, err
  585. }
  586. b, err = readNBytes(r, 64)
  587. if err != nil {
  588. return nil, err
  589. }
  590. pk.VkBeta1 = new(bn256.G1)
  591. _, err = pk.VkBeta1.Unmarshal(fromMont1Q(b))
  592. if err != nil {
  593. return nil, err
  594. }
  595. b, err = readNBytes(r, 64)
  596. if err != nil {
  597. return nil, err
  598. }
  599. pk.VkDelta1 = new(bn256.G1)
  600. _, err = pk.VkDelta1.Unmarshal(fromMont1Q(b))
  601. if err != nil {
  602. return nil, err
  603. }
  604. b, err = readNBytes(r, 128)
  605. if err != nil {
  606. return nil, err
  607. }
  608. pk.VkBeta2 = new(bn256.G2)
  609. _, err = pk.VkBeta2.Unmarshal(fromMont2Q(b))
  610. if err != nil {
  611. return nil, err
  612. }
  613. b, err = readNBytes(r, 128)
  614. if err != nil {
  615. return nil, err
  616. }
  617. pk.VkDelta2 = new(bn256.G2)
  618. _, err = pk.VkDelta2.Unmarshal(fromMont2Q(b))
  619. if err != nil {
  620. return nil, err
  621. }
  622. o += 448
  623. if o != pPolsA {
  624. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsA, o)
  625. }
  626. // PolsA
  627. for i := 0; i < pk.NVars; i++ {
  628. b, err = readNBytes(r, 4)
  629. if err != nil {
  630. return nil, err
  631. }
  632. keysLength := int(binary.LittleEndian.Uint32(b[:4]))
  633. o += 4
  634. polsMap := make(map[int]*big.Int)
  635. for j := 0; j < keysLength; j++ {
  636. bK, err := readNBytes(r, 4)
  637. if err != nil {
  638. return nil, err
  639. }
  640. key := int(binary.LittleEndian.Uint32(bK[:4]))
  641. o += 4
  642. b, err := readNBytes(r, 32)
  643. if err != nil {
  644. return nil, err
  645. }
  646. polsMap[key] = new(big.Int).SetBytes(fromMont1R(b[:32]))
  647. o += 32
  648. }
  649. pk.PolsA = append(pk.PolsA, polsMap)
  650. }
  651. if o != pPolsB {
  652. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsB, o)
  653. }
  654. // PolsB
  655. for i := 0; i < pk.NVars; i++ {
  656. b, err = readNBytes(r, 4)
  657. if err != nil {
  658. return nil, err
  659. }
  660. keysLength := int(binary.LittleEndian.Uint32(b[:4]))
  661. o += 4
  662. polsMap := make(map[int]*big.Int)
  663. for j := 0; j < keysLength; j++ {
  664. bK, err := readNBytes(r, 4)
  665. if err != nil {
  666. return nil, err
  667. }
  668. key := int(binary.LittleEndian.Uint32(bK[:4]))
  669. o += 4
  670. b, err := readNBytes(r, 32)
  671. if err != nil {
  672. return nil, err
  673. }
  674. polsMap[key] = new(big.Int).SetBytes(fromMont1R(b[:32]))
  675. o += 32
  676. }
  677. pk.PolsB = append(pk.PolsB, polsMap)
  678. }
  679. if o != pPointsA {
  680. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsA, o)
  681. }
  682. // A
  683. for i := 0; i < pk.NVars; i++ {
  684. b, err = readNBytes(r, 64)
  685. if err != nil {
  686. return nil, err
  687. }
  688. p1 := new(bn256.G1)
  689. _, err = p1.Unmarshal(fromMont1Q(b))
  690. if err != nil {
  691. return nil, err
  692. }
  693. pk.A = append(pk.A, p1)
  694. o += 64
  695. }
  696. if o != pPointsB1 {
  697. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB1, o)
  698. }
  699. // B1
  700. for i := 0; i < pk.NVars; i++ {
  701. b, err = readNBytes(r, 64)
  702. if err != nil {
  703. return nil, err
  704. }
  705. p1 := new(bn256.G1)
  706. _, err = p1.Unmarshal(fromMont1Q(b))
  707. if err != nil {
  708. return nil, err
  709. }
  710. pk.B1 = append(pk.B1, p1)
  711. o += 64
  712. }
  713. if o != pPointsB2 {
  714. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB2, o)
  715. }
  716. // B2
  717. for i := 0; i < pk.NVars; i++ {
  718. b, err = readNBytes(r, 128)
  719. if err != nil {
  720. return nil, err
  721. }
  722. p2 := new(bn256.G2)
  723. _, err = p2.Unmarshal(fromMont2Q(b))
  724. if err != nil {
  725. return nil, err
  726. }
  727. pk.B2 = append(pk.B2, p2)
  728. o += 128
  729. }
  730. if o != pPointsC {
  731. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsC, o)
  732. }
  733. // C
  734. zb := make([]byte, 64)
  735. z := new(bn256.G1)
  736. _, err = z.Unmarshal(zb)
  737. if err != nil {
  738. return nil, err
  739. }
  740. for i := 0; i < pk.NPublic+1; i++ {
  741. pk.C = append(pk.C, z)
  742. }
  743. for i := pk.NPublic + 1; i < pk.NVars; i++ {
  744. b, err = readNBytes(r, 64)
  745. if err != nil {
  746. return nil, err
  747. }
  748. p1 := new(bn256.G1)
  749. _, err = p1.Unmarshal(fromMont1Q(b))
  750. if err != nil {
  751. return nil, err
  752. }
  753. pk.C = append(pk.C, p1)
  754. o += 64
  755. }
  756. if o != pPointsHExps {
  757. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsHExps, o)
  758. }
  759. // HExps
  760. for i := 0; i < pk.DomainSize; i++ {
  761. b, err = readNBytes(r, 64)
  762. if err != nil {
  763. return nil, err
  764. }
  765. p1 := new(bn256.G1)
  766. _, err = p1.Unmarshal(fromMont1Q(b))
  767. if err != nil {
  768. return nil, err
  769. }
  770. pk.HExps = append(pk.HExps, p1)
  771. }
  772. return &pk, nil
  773. }
  774. func fromMont1Q(m []byte) []byte {
  775. a := new(big.Int).SetBytes(swapEndianness(m[:32]))
  776. b := new(big.Int).SetBytes(swapEndianness(m[32:64]))
  777. x := coordFromMont(a, types.Q)
  778. y := coordFromMont(b, types.Q)
  779. if bytes.Equal(x.Bytes(), big.NewInt(1).Bytes()) {
  780. x = big.NewInt(0)
  781. }
  782. if bytes.Equal(y.Bytes(), big.NewInt(1).Bytes()) {
  783. y = big.NewInt(0)
  784. }
  785. xBytes := x.Bytes()
  786. yBytes := y.Bytes()
  787. if len(xBytes) != 32 {
  788. xBytes = addZPadding(xBytes)
  789. }
  790. if len(yBytes) != 32 {
  791. yBytes = addZPadding(yBytes)
  792. }
  793. var p []byte
  794. p = append(p, xBytes...)
  795. p = append(p, yBytes...)
  796. return p
  797. }
  798. func fromMont2Q(m []byte) []byte {
  799. a := new(big.Int).SetBytes(swapEndianness(m[:32]))
  800. b := new(big.Int).SetBytes(swapEndianness(m[32:64]))
  801. c := new(big.Int).SetBytes(swapEndianness(m[64:96]))
  802. d := new(big.Int).SetBytes(swapEndianness(m[96:128]))
  803. x := coordFromMont(a, types.Q)
  804. y := coordFromMont(b, types.Q)
  805. z := coordFromMont(c, types.Q)
  806. t := coordFromMont(d, types.Q)
  807. if bytes.Equal(x.Bytes(), big.NewInt(1).Bytes()) {
  808. x = big.NewInt(0)
  809. }
  810. if bytes.Equal(y.Bytes(), big.NewInt(1).Bytes()) {
  811. y = big.NewInt(0)
  812. }
  813. if bytes.Equal(z.Bytes(), big.NewInt(1).Bytes()) {
  814. z = big.NewInt(0)
  815. }
  816. if bytes.Equal(t.Bytes(), big.NewInt(1).Bytes()) {
  817. t = big.NewInt(0)
  818. }
  819. xBytes := x.Bytes()
  820. yBytes := y.Bytes()
  821. zBytes := z.Bytes()
  822. tBytes := t.Bytes()
  823. if len(xBytes) != 32 {
  824. xBytes = addZPadding(xBytes)
  825. }
  826. if len(yBytes) != 32 {
  827. yBytes = addZPadding(yBytes)
  828. }
  829. if len(zBytes) != 32 {
  830. zBytes = addZPadding(zBytes)
  831. }
  832. if len(tBytes) != 32 {
  833. tBytes = addZPadding(tBytes)
  834. }
  835. var p []byte
  836. p = append(p, yBytes...) // swap
  837. p = append(p, xBytes...)
  838. p = append(p, tBytes...)
  839. p = append(p, zBytes...)
  840. return p
  841. }
  842. func fromMont1R(m []byte) []byte {
  843. a := new(big.Int).SetBytes(swapEndianness(m[:32]))
  844. x := coordFromMont(a, types.R)
  845. return x.Bytes()
  846. }
  847. func fromMont2R(m []byte) []byte {
  848. a := new(big.Int).SetBytes(swapEndianness(m[:32]))
  849. b := new(big.Int).SetBytes(swapEndianness(m[32:64]))
  850. c := new(big.Int).SetBytes(swapEndianness(m[64:96]))
  851. d := new(big.Int).SetBytes(swapEndianness(m[96:128]))
  852. x := coordFromMont(a, types.R)
  853. y := coordFromMont(b, types.R)
  854. z := coordFromMont(c, types.R)
  855. t := coordFromMont(d, types.R)
  856. var p []byte
  857. p = append(p, y.Bytes()...) // swap
  858. p = append(p, x.Bytes()...)
  859. p = append(p, t.Bytes()...)
  860. p = append(p, z.Bytes()...)
  861. return p
  862. }
  863. func coordFromMont(u, q *big.Int) *big.Int {
  864. return new(big.Int).Mod(
  865. new(big.Int).Mul(
  866. u,
  867. new(big.Int).ModInverse(
  868. new(big.Int).Lsh(big.NewInt(1), 256),
  869. q,
  870. ),
  871. ),
  872. q,
  873. )
  874. }
  875. func sortedKeys(m map[int]*big.Int) []int {
  876. keys := make([]int, 0, len(m))
  877. for k, _ := range m {
  878. keys = append(keys, k)
  879. }
  880. sort.Ints(keys)
  881. return keys
  882. }
  883. // PkToGoBin converts the ProvingKey (*types.Pk) into binary format defined by
  884. // go-circom-prover-verifier. PkGoBin is a own go-circom-prover-verifier
  885. // binary format that allows to go faster when parsing.
  886. func PkToGoBin(pk *types.Pk) ([]byte, error) {
  887. var r []byte
  888. o := 0
  889. var b [4]byte
  890. binary.LittleEndian.PutUint32(b[:], uint32(pk.NVars))
  891. r = append(r, b[:]...)
  892. binary.LittleEndian.PutUint32(b[:], uint32(pk.NPublic))
  893. r = append(r, b[:]...)
  894. binary.LittleEndian.PutUint32(b[:], uint32(pk.DomainSize))
  895. r = append(r, b[:]...)
  896. o += 12
  897. // reserve space for pols (A, B) pos
  898. b = [4]byte{}
  899. r = append(r, b[:]...) // 12:16
  900. r = append(r, b[:]...) // 16:20
  901. o += 8
  902. // reserve space for points (A, B1, B2, C, HExps) pos
  903. r = append(r, b[:]...) // 20:24
  904. r = append(r, b[:]...) // 24
  905. r = append(r, b[:]...) // 28
  906. r = append(r, b[:]...) // 32
  907. r = append(r, b[:]...) // 36:40
  908. o += 20
  909. pb1 := pk.VkAlpha1.Marshal()
  910. r = append(r, pb1[:]...)
  911. pb1 = pk.VkBeta1.Marshal()
  912. r = append(r, pb1[:]...)
  913. pb1 = pk.VkDelta1.Marshal()
  914. r = append(r, pb1[:]...)
  915. pb2 := pk.VkBeta2.Marshal()
  916. r = append(r, pb2[:]...)
  917. pb2 = pk.VkDelta2.Marshal()
  918. r = append(r, pb2[:]...)
  919. o += 448
  920. // polsA
  921. binary.LittleEndian.PutUint32(r[12:16], uint32(o))
  922. for i := 0; i < pk.NVars; i++ {
  923. binary.LittleEndian.PutUint32(b[:], uint32(len(pk.PolsA[i])))
  924. r = append(r, b[:]...)
  925. o += 4
  926. for _, j := range sortedKeys(pk.PolsA[i]) {
  927. v := pk.PolsA[i][j]
  928. binary.LittleEndian.PutUint32(b[:], uint32(j))
  929. r = append(r, b[:]...)
  930. r = append(r, addPadding32(v.Bytes())...)
  931. o += 32 + 4
  932. }
  933. }
  934. // polsB
  935. binary.LittleEndian.PutUint32(r[16:20], uint32(o))
  936. for i := 0; i < pk.NVars; i++ {
  937. binary.LittleEndian.PutUint32(b[:], uint32(len(pk.PolsB[i])))
  938. r = append(r, b[:]...)
  939. o += 4
  940. for _, j := range sortedKeys(pk.PolsB[i]) {
  941. v := pk.PolsB[i][j]
  942. binary.LittleEndian.PutUint32(b[:], uint32(j))
  943. r = append(r, b[:]...)
  944. r = append(r, addPadding32(v.Bytes())...)
  945. o += 32 + 4
  946. }
  947. }
  948. // A
  949. binary.LittleEndian.PutUint32(r[20:24], uint32(o))
  950. for i := 0; i < pk.NVars; i++ {
  951. pb1 = pk.A[i].Marshal()
  952. r = append(r, pb1[:]...)
  953. o += 64
  954. }
  955. // B1
  956. binary.LittleEndian.PutUint32(r[24:28], uint32(o))
  957. for i := 0; i < pk.NVars; i++ {
  958. pb1 = pk.B1[i].Marshal()
  959. r = append(r, pb1[:]...)
  960. o += 64
  961. }
  962. // B2
  963. binary.LittleEndian.PutUint32(r[28:32], uint32(o))
  964. for i := 0; i < pk.NVars; i++ {
  965. pb2 = pk.B2[i].Marshal()
  966. r = append(r, pb2[:]...)
  967. o += 128
  968. }
  969. // C
  970. binary.LittleEndian.PutUint32(r[32:36], uint32(o))
  971. for i := pk.NPublic + 1; i < pk.NVars; i++ {
  972. pb1 = pk.C[i].Marshal()
  973. r = append(r, pb1[:]...)
  974. o += 64
  975. }
  976. // HExps
  977. binary.LittleEndian.PutUint32(r[36:40], uint32(o))
  978. for i := 0; i < pk.DomainSize+1; i++ {
  979. pb1 = pk.HExps[i].Marshal()
  980. r = append(r, pb1[:]...)
  981. o += 64
  982. }
  983. return r[:], nil
  984. }
  985. // ParsePkGoBin parses go-circom-prover-verifier binary file representation of
  986. // the ProvingKey into ProvingKey struct (*types.Pk). PkGoBin is a own
  987. // go-circom-prover-verifier binary format that allows to go faster when
  988. // parsing.
  989. func ParsePkGoBin(f *os.File) (*types.Pk, error) {
  990. o := 0
  991. var pk types.Pk
  992. r := bufio.NewReader(f)
  993. b, err := readNBytes(r, 12)
  994. if err != nil {
  995. return nil, err
  996. }
  997. pk.NVars = int(binary.LittleEndian.Uint32(b[:4]))
  998. pk.NPublic = int(binary.LittleEndian.Uint32(b[4:8]))
  999. pk.DomainSize = int(binary.LittleEndian.Uint32(b[8:12]))
  1000. o += 12
  1001. b, err = readNBytes(r, 8)
  1002. if err != nil {
  1003. return nil, err
  1004. }
  1005. pPolsA := int(binary.LittleEndian.Uint32(b[:4]))
  1006. pPolsB := int(binary.LittleEndian.Uint32(b[4:8]))
  1007. o += 8
  1008. b, err = readNBytes(r, 20)
  1009. if err != nil {
  1010. return nil, err
  1011. }
  1012. pPointsA := int(binary.LittleEndian.Uint32(b[:4]))
  1013. pPointsB1 := int(binary.LittleEndian.Uint32(b[4:8]))
  1014. pPointsB2 := int(binary.LittleEndian.Uint32(b[8:12]))
  1015. pPointsC := int(binary.LittleEndian.Uint32(b[12:16]))
  1016. pPointsHExps := int(binary.LittleEndian.Uint32(b[16:20]))
  1017. o += 20
  1018. b, err = readNBytes(r, 64)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. pk.VkAlpha1 = new(bn256.G1)
  1023. _, err = pk.VkAlpha1.Unmarshal(b)
  1024. if err != nil {
  1025. return &pk, err
  1026. }
  1027. b, err = readNBytes(r, 64)
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. pk.VkBeta1 = new(bn256.G1)
  1032. _, err = pk.VkBeta1.Unmarshal(b)
  1033. if err != nil {
  1034. return &pk, err
  1035. }
  1036. b, err = readNBytes(r, 64)
  1037. if err != nil {
  1038. return nil, err
  1039. }
  1040. pk.VkDelta1 = new(bn256.G1)
  1041. _, err = pk.VkDelta1.Unmarshal(b)
  1042. if err != nil {
  1043. return &pk, err
  1044. }
  1045. b, err = readNBytes(r, 128)
  1046. if err != nil {
  1047. return nil, err
  1048. }
  1049. pk.VkBeta2 = new(bn256.G2)
  1050. _, err = pk.VkBeta2.Unmarshal(b)
  1051. if err != nil {
  1052. return &pk, err
  1053. }
  1054. b, err = readNBytes(r, 128)
  1055. if err != nil {
  1056. return nil, err
  1057. }
  1058. pk.VkDelta2 = new(bn256.G2)
  1059. _, err = pk.VkDelta2.Unmarshal(b)
  1060. if err != nil {
  1061. return &pk, err
  1062. }
  1063. o += 448
  1064. if o != pPolsA {
  1065. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsA, o)
  1066. }
  1067. // PolsA
  1068. for i := 0; i < pk.NVars; i++ {
  1069. b, err = readNBytes(r, 4)
  1070. if err != nil {
  1071. return nil, err
  1072. }
  1073. keysLength := int(binary.LittleEndian.Uint32(b[:4]))
  1074. o += 4
  1075. polsMap := make(map[int]*big.Int)
  1076. for j := 0; j < keysLength; j++ {
  1077. bK, err := readNBytes(r, 4)
  1078. if err != nil {
  1079. return nil, err
  1080. }
  1081. key := int(binary.LittleEndian.Uint32(bK[:4]))
  1082. o += 4
  1083. b, err := readNBytes(r, 32)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. polsMap[key] = new(big.Int).SetBytes(b[:32])
  1088. o += 32
  1089. }
  1090. pk.PolsA = append(pk.PolsA, polsMap)
  1091. }
  1092. if o != pPolsB {
  1093. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsB, o)
  1094. }
  1095. // PolsB
  1096. for i := 0; i < pk.NVars; i++ {
  1097. b, err = readNBytes(r, 4)
  1098. if err != nil {
  1099. return nil, err
  1100. }
  1101. keysLength := int(binary.LittleEndian.Uint32(b[:4]))
  1102. o += 4
  1103. polsMap := make(map[int]*big.Int)
  1104. for j := 0; j < keysLength; j++ {
  1105. bK, err := readNBytes(r, 4)
  1106. if err != nil {
  1107. return nil, err
  1108. }
  1109. key := int(binary.LittleEndian.Uint32(bK[:4]))
  1110. o += 4
  1111. b, err := readNBytes(r, 32)
  1112. if err != nil {
  1113. return nil, err
  1114. }
  1115. polsMap[key] = new(big.Int).SetBytes(b[:32])
  1116. o += 32
  1117. }
  1118. pk.PolsB = append(pk.PolsB, polsMap)
  1119. }
  1120. if o != pPointsA {
  1121. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsA, o)
  1122. }
  1123. // A
  1124. for i := 0; i < pk.NVars; i++ {
  1125. b, err = readNBytes(r, 64)
  1126. if err != nil {
  1127. return nil, err
  1128. }
  1129. p1 := new(bn256.G1)
  1130. _, err = p1.Unmarshal(b)
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. pk.A = append(pk.A, p1)
  1135. o += 64
  1136. }
  1137. if o != pPointsB1 {
  1138. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB1, o)
  1139. }
  1140. // B1
  1141. for i := 0; i < pk.NVars; i++ {
  1142. b, err = readNBytes(r, 64)
  1143. if err != nil {
  1144. return nil, err
  1145. }
  1146. p1 := new(bn256.G1)
  1147. _, err = p1.Unmarshal(b)
  1148. if err != nil {
  1149. return nil, err
  1150. }
  1151. pk.B1 = append(pk.B1, p1)
  1152. o += 64
  1153. }
  1154. if o != pPointsB2 {
  1155. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB2, o)
  1156. }
  1157. // B2
  1158. for i := 0; i < pk.NVars; i++ {
  1159. b, err = readNBytes(r, 128)
  1160. if err != nil {
  1161. return nil, err
  1162. }
  1163. p2 := new(bn256.G2)
  1164. _, err = p2.Unmarshal(b)
  1165. if err != nil {
  1166. return nil, err
  1167. }
  1168. pk.B2 = append(pk.B2, p2)
  1169. o += 128
  1170. }
  1171. if o != pPointsC {
  1172. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsC, o)
  1173. }
  1174. // C
  1175. zb := make([]byte, 64)
  1176. z := new(bn256.G1)
  1177. _, err = z.Unmarshal(zb)
  1178. if err != nil {
  1179. return nil, err
  1180. }
  1181. for i := 0; i < pk.NPublic+1; i++ {
  1182. pk.C = append(pk.C, z)
  1183. }
  1184. for i := pk.NPublic + 1; i < pk.NVars; i++ {
  1185. b, err = readNBytes(r, 64)
  1186. if err != nil {
  1187. return nil, err
  1188. }
  1189. p1 := new(bn256.G1)
  1190. _, err = p1.Unmarshal(b)
  1191. if err != nil {
  1192. return nil, err
  1193. }
  1194. pk.C = append(pk.C, p1)
  1195. o += 64
  1196. }
  1197. if o != pPointsHExps {
  1198. return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsHExps, o)
  1199. }
  1200. // HExps
  1201. for i := 0; i < pk.DomainSize+1; i++ {
  1202. b, err = readNBytes(r, 64)
  1203. if err != nil {
  1204. return nil, err
  1205. }
  1206. p1 := new(bn256.G1)
  1207. _, err = p1.Unmarshal(b)
  1208. if err != nil {
  1209. return nil, err
  1210. }
  1211. pk.HExps = append(pk.HExps, p1)
  1212. }
  1213. return &pk, nil
  1214. }