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.

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