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.

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