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.

611 lines
18 KiB

  1. package circuitcompiler
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "github.com/arnaucube/go-snark/bn128"
  6. "github.com/arnaucube/go-snark/fields"
  7. "github.com/arnaucube/go-snark/r1csqap"
  8. "math/big"
  9. "sync"
  10. )
  11. type utils struct {
  12. Bn bn128.Bn128
  13. FqR fields.Fq
  14. PF r1csqap.PolynomialField
  15. }
  16. type R1CS struct {
  17. A [][]*big.Int
  18. B [][]*big.Int
  19. C [][]*big.Int
  20. }
  21. type Program struct {
  22. functions map[string]*Circuit
  23. globalInputs []string
  24. arithmeticEnvironment utils //find a better name
  25. //key 1: the hash chain indicating from where the variable is called H( H(main(a,b)) , doSomething(x,z) ), where H is a hash function.
  26. //value 1 : map
  27. // with key variable name
  28. // with value variable name + hash Chain
  29. //this datastructure is nice but maybe ill replace it later with something less confusing
  30. //it serves the elementary purpose of not computing a variable a second time.
  31. //it boosts parse time
  32. computedInContext map[string]map[string]string
  33. //to reduce the number of multiplication gates, we store each factor signature, and the variable name,
  34. //so each time a variable is computed, that happens to have the very same factors, we reuse the former
  35. //it boost setup and proof time
  36. computedFactors map[string]string
  37. }
  38. func (p *Program) GlobalInputCount() int {
  39. return len(p.globalInputs)
  40. }
  41. func (p *Program) PrintContraintTrees() {
  42. for k, v := range p.functions {
  43. fmt.Println(k)
  44. PrintTree(v.root)
  45. }
  46. }
  47. func (p *Program) BuildConstraintTrees() {
  48. mainRoot := p.getMainCircuit().root
  49. //if our programs last operation is not a multiplication gate, we need to introduce on
  50. if mainRoot.value.Op&(MINUS|PLUS) != 0 {
  51. newOut := Constraint{Out: "out", V1: "1", V2: "out2", Op: MULTIPLY}
  52. p.getMainCircuit().addConstraint(&newOut)
  53. mainRoot.value.Out = "main@out2"
  54. p.getMainCircuit().gateMap[mainRoot.value.Out] = mainRoot
  55. }
  56. for _, in := range p.getMainCircuit().Inputs {
  57. p.globalInputs = append(p.globalInputs, in)
  58. }
  59. var wg = sync.WaitGroup{}
  60. //we build the parse trees concurrently! because we can! go rocks
  61. for _, circuit := range p.functions {
  62. wg.Add(1)
  63. //interesting: if circuit is not passed as argument, the program fails. duno why..
  64. go func(c *Circuit) {
  65. c.buildTree(c.root)
  66. wg.Done()
  67. }(circuit)
  68. }
  69. wg.Wait()
  70. return
  71. }
  72. func (c *Circuit) buildTree(g *gate) {
  73. if _, ex := c.gateMap[g.value.Out]; ex {
  74. if g.OperationType()&(IN|CONST) != 0 {
  75. return
  76. }
  77. } else {
  78. panic(fmt.Sprintf("undefined variable %s", g.value.Out))
  79. }
  80. if g.OperationType() == FUNC {
  81. for _, in := range g.value.Inputs {
  82. if gate, ex := c.gateMap[in]; ex {
  83. g.funcInputs = append(g.funcInputs, gate)
  84. c.buildTree(gate)
  85. } else {
  86. panic(fmt.Sprintf("undefined argument %s", g.value.V1))
  87. }
  88. }
  89. return
  90. }
  91. if constr, ex := c.gateMap[g.value.V1]; ex {
  92. g.left = constr
  93. c.buildTree(g.left)
  94. } else {
  95. panic(fmt.Sprintf("undefined value %s", g.value.V1))
  96. }
  97. if constr, ex := c.gateMap[g.value.V2]; ex {
  98. g.right = constr
  99. c.buildTree(g.right)
  100. } else {
  101. panic(fmt.Sprintf("undefined value %s", g.value.V2))
  102. }
  103. }
  104. func (p *Program) ReduceCombinedTree() (orderedmGates []gate) {
  105. orderedmGates = []gate{}
  106. p.computedInContext = make(map[string]map[string]string)
  107. p.computedFactors = make(map[string]string)
  108. rootHash := []byte{}
  109. p.computedInContext[string(rootHash)] = make(map[string]string)
  110. p.r1CSRecursiveBuild(p.getMainCircuit(), p.getMainCircuit().root, rootHash, &orderedmGates, false, false)
  111. return orderedmGates
  112. }
  113. //recursively walks through the parse tree to create a list of all
  114. //multiplication gates needed for the QAP construction
  115. //Takes into account, that multiplication with constants and addition (= substraction) can be reduced, and does so
  116. func (p *Program) r1CSRecursiveBuild(currentCircuit *Circuit, node *gate, hashTraceBuildup []byte, orderedmGates *[]gate, negate bool, invert bool) (facs []factor, hashTraceResult []byte, variableEnd bool) {
  117. if node.OperationType() == CONST {
  118. b1, v1 := isValue(node.value.Out)
  119. if !b1 {
  120. panic("not a constant")
  121. }
  122. mul := [2]int{v1, 1}
  123. if invert {
  124. mul = [2]int{1, v1}
  125. }
  126. return []factor{{typ: CONST, negate: negate, multiplicative: mul}}, make([]byte, 10), false
  127. }
  128. if node.OperationType() == FUNC {
  129. nextContext := p.extendedFunctionRenamer(currentCircuit, node.value)
  130. currentCircuit = nextContext
  131. node = nextContext.root
  132. hashTraceBuildup = hashTogether(hashTraceBuildup, []byte(currentCircuit.currentOutputName()))
  133. if _, ex := p.computedInContext[string(hashTraceBuildup)]; !ex {
  134. p.computedInContext[string(hashTraceBuildup)] = make(map[string]string)
  135. }
  136. }
  137. if node.OperationType() == IN {
  138. fac := factor{typ: IN, name: node.value.Out, invert: invert, negate: negate, multiplicative: [2]int{1, 1}}
  139. hashTraceBuildup = hashTogether(hashTraceBuildup, []byte(node.value.Out))
  140. return []factor{fac}, hashTraceBuildup, true
  141. }
  142. if out, ex := p.computedInContext[string(hashTraceBuildup)][node.value.Out]; ex {
  143. fac := factor{typ: IN, name: out, invert: invert, negate: negate, multiplicative: [2]int{1, 1}}
  144. hashTraceBuildup = hashTogether(hashTraceBuildup, []byte(node.value.Out))
  145. return []factor{fac}, hashTraceBuildup, true
  146. }
  147. leftFactors, leftHash, variableEnd := p.r1CSRecursiveBuild(currentCircuit, node.left, hashTraceBuildup, orderedmGates, negate, invert)
  148. rightFactors, rightHash, cons := p.r1CSRecursiveBuild(currentCircuit, node.right, hashTraceBuildup, orderedmGates, Xor(negate, node.value.negate), Xor(invert, node.value.invert))
  149. if node.OperationType() == MULTIPLY {
  150. if !(variableEnd && cons) && !node.value.invert && node != p.getMainCircuit().root {
  151. //if !(variableEnd && cons) && !node.value.invert && node != p.getMainCircuit().root {
  152. return mulFactors(leftFactors, rightFactors), append(leftHash, rightHash...), variableEnd || cons
  153. }
  154. sig := factorsSignature(leftFactors, rightFactors)
  155. if out, ex := p.computedFactors[sig]; ex {
  156. return []factor{{typ: IN, name: out, invert: invert, negate: negate, multiplicative: [2]int{1, 1}}}, hashTraceBuildup, true
  157. }
  158. rootGate := cloneGate(node)
  159. rootGate.index = len(*orderedmGates)
  160. rootGate.leftIns = leftFactors
  161. rootGate.rightIns = rightFactors
  162. out := hashTogether(leftHash, rightHash)
  163. rootGate.value.V1 = rootGate.value.V1 + string(leftHash[:10])
  164. rootGate.value.V2 = rootGate.value.V2 + string(rightHash[:10])
  165. rootGate.value.Out = rootGate.value.Out + string(out[:10])
  166. p.computedInContext[string(hashTraceBuildup)][node.value.Out] = rootGate.value.Out
  167. p.computedFactors[sig] = rootGate.value.Out
  168. *orderedmGates = append(*orderedmGates, *rootGate)
  169. hashTraceBuildup = hashTogether(hashTraceBuildup, []byte(rootGate.value.Out))
  170. return []factor{{typ: IN, name: rootGate.value.Out, invert: invert, negate: negate, multiplicative: [2]int{1, 1}}}, hashTraceBuildup, true
  171. }
  172. switch node.OperationType() {
  173. case PLUS:
  174. return addFactors(leftFactors, rightFactors), hashTogether(leftHash, rightHash), variableEnd || cons
  175. default:
  176. panic("unexpected gate")
  177. }
  178. }
  179. type factor struct {
  180. typ Token
  181. name string
  182. invert, negate bool
  183. multiplicative [2]int
  184. }
  185. func (f factor) String() string {
  186. if f.typ == CONST {
  187. return fmt.Sprintf("(const fac: %v)", f.multiplicative)
  188. }
  189. str := f.name
  190. if f.invert {
  191. str += "^-1"
  192. }
  193. if f.negate {
  194. str = "-" + str
  195. }
  196. return fmt.Sprintf("(\"%s\" fac: %v)", str, f.multiplicative)
  197. }
  198. func mul2DVector(a, b [2]int) [2]int {
  199. return [2]int{a[0] * b[0], a[1] * b[1]}
  200. }
  201. func factorsSignature(leftFactors, rightFactors []factor) string {
  202. hasher.Reset()
  203. //using a commutative operation here would be better. since a * b = b * a, but H(a,b) != H(b,a)
  204. //could use (g^a)^b == (g^b)^a where g is a generator of some prime field where the dicrete log is known to be hard
  205. for _, facLeft := range leftFactors {
  206. hasher.Write([]byte(facLeft.String()))
  207. }
  208. for _, Righ := range rightFactors {
  209. hasher.Write([]byte(Righ.String()))
  210. }
  211. return string(hasher.Sum(nil))[:16]
  212. }
  213. //multiplies factor elements and returns the result
  214. //in case the factors do not hold any constants and all inputs are distinct, the output will be the concatenation of left+right
  215. func mulFactors(leftFactors, rightFactors []factor) (result []factor) {
  216. for _, facLeft := range leftFactors {
  217. for i, facRight := range rightFactors {
  218. if facLeft.typ == CONST && facRight.typ == IN {
  219. rightFactors[i] = factor{typ: IN, name: facRight.name, negate: Xor(facLeft.negate, facRight.negate), invert: facRight.invert, multiplicative: mul2DVector(facRight.multiplicative, facLeft.multiplicative)}
  220. continue
  221. }
  222. if facRight.typ == CONST && facLeft.typ == IN {
  223. rightFactors[i] = factor{typ: IN, name: facLeft.name, negate: Xor(facLeft.negate, facRight.negate), invert: facLeft.invert, multiplicative: mul2DVector(facRight.multiplicative, facLeft.multiplicative)}
  224. continue
  225. }
  226. if facRight.typ&facLeft.typ == CONST {
  227. rightFactors[i] = factor{typ: CONST, negate: Xor(facRight.negate, facLeft.negate), multiplicative: mul2DVector(facRight.multiplicative, facLeft.multiplicative)}
  228. continue
  229. }
  230. //tricky part here
  231. //this one should only be reached, after a true mgate had its left and right braches computed. here we
  232. //a factor can appear at most in quadratic form. we reduce terms a*a^-1 here.
  233. if facRight.typ&facLeft.typ == IN {
  234. if facLeft.name == facRight.name {
  235. if facRight.invert != facLeft.invert {
  236. rightFactors[i] = factor{typ: CONST, negate: Xor(facRight.negate, facLeft.negate), multiplicative: mul2DVector(facRight.multiplicative, facLeft.multiplicative)}
  237. continue
  238. }
  239. }
  240. //rightFactors[i] = factor{typ: CONST, negate: Xor(facRight.negate, facLeft.negate), multiplicative: mul2DVector(facRight.multiplicative, facLeft.multiplicative)}
  241. //continue
  242. }
  243. panic("unexpected. If this errror is thrown, its probably brcause a true multiplication gate has been skipped and treated as on with constant multiplication or addition ")
  244. }
  245. }
  246. return rightFactors
  247. }
  248. //returns the absolute value of a signed int and a flag telling if the input was positive or not
  249. //this implementation is awesome and fast (see Henry S Warren, Hackers's Delight)
  250. func abs(n int) (val int, positive bool) {
  251. y := n >> 63
  252. return (n ^ y) - y, y == 0
  253. }
  254. //returns the reduced sum of two input factor arrays
  255. //if no reduction was done (worst case), it returns the concatenation of the input arrays
  256. func addFactors(leftFactors, rightFactors []factor) []factor {
  257. var found bool
  258. res := make([]factor, 0, len(leftFactors)+len(rightFactors))
  259. for _, facLeft := range leftFactors {
  260. found = false
  261. for i, facRight := range rightFactors {
  262. if facLeft.typ&facRight.typ == CONST {
  263. var a0, b0 = facLeft.multiplicative[0], facRight.multiplicative[0]
  264. if facLeft.negate {
  265. a0 *= -1
  266. }
  267. if facRight.negate {
  268. b0 *= -1
  269. }
  270. absValue, positive := abs(a0*facRight.multiplicative[1] + facLeft.multiplicative[1]*b0)
  271. rightFactors[i] = factor{typ: CONST, negate: !positive, multiplicative: [2]int{absValue, facLeft.multiplicative[1] * facRight.multiplicative[1]}}
  272. found = true
  273. //res = append(res, factor{typ: CONST, negate: negate, multiplicative: [2]int{absValue, facLeft.multiplicative[1] * facRight.multiplicative[1]}})
  274. break
  275. }
  276. if facLeft.typ&facRight.typ == IN && facLeft.invert == facRight.invert && facLeft.name == facRight.name {
  277. var a0, b0 = facLeft.multiplicative[0], facRight.multiplicative[0]
  278. if facLeft.negate {
  279. a0 *= -1
  280. }
  281. if facRight.negate {
  282. b0 *= -1
  283. }
  284. absValue, positive := abs(a0*facRight.multiplicative[1] + facLeft.multiplicative[1]*b0)
  285. rightFactors[i] = factor{typ: IN, invert: facRight.invert, name: facRight.name, negate: !positive, multiplicative: [2]int{absValue, facLeft.multiplicative[1] * facRight.multiplicative[1]}}
  286. found = true
  287. //res = append(res, factor{typ: CONST, negate: negate, multiplicative: [2]int{absValue, facLeft.multiplicative[1] * facRight.multiplicative[1]}})
  288. break
  289. }
  290. }
  291. if !found {
  292. res = append(res, facLeft)
  293. }
  294. }
  295. for _, val := range rightFactors {
  296. if val.multiplicative[0] != 0 {
  297. res = append(res, val)
  298. }
  299. }
  300. return res
  301. }
  302. //copies a gate neglecting its references to other gates
  303. func cloneGate(in *gate) (out *gate) {
  304. constr := &Constraint{Inputs: in.value.Inputs, Out: in.value.Out, Op: in.value.Op, invert: in.value.invert, negate: in.value.negate, V2: in.value.V2, V1: in.value.V1}
  305. nRightins := make([]factor, len(in.rightIns))
  306. nLeftInst := make([]factor, len(in.leftIns))
  307. for k, v := range in.rightIns {
  308. nRightins[k] = v
  309. }
  310. for k, v := range in.leftIns {
  311. nLeftInst[k] = v
  312. }
  313. return &gate{value: constr, leftIns: nLeftInst, rightIns: nRightins, index: in.index}
  314. }
  315. func (p *Program) getMainCircuit() *Circuit {
  316. return p.functions["main"]
  317. }
  318. func prepareUtils() utils {
  319. bn, err := bn128.NewBn128()
  320. if err != nil {
  321. panic(err)
  322. }
  323. // new Finite Field
  324. fqR := fields.NewFq(bn.R)
  325. // new Polynomial Field
  326. pf := r1csqap.NewPolynomialField(fqR)
  327. return utils{
  328. Bn: bn,
  329. FqR: fqR,
  330. PF: pf,
  331. }
  332. }
  333. func (p *Program) extendedFunctionRenamer(contextCircuit *Circuit, constraint *Constraint) (nextContext *Circuit) {
  334. if constraint.Op != FUNC {
  335. panic("not a function")
  336. }
  337. //if _, ex := contextCircuit.gateMap[constraint.Out]; !ex {
  338. // panic("constraint must be within the contextCircuit circuit")
  339. //}
  340. b, n, _ := isFunction(constraint.Out)
  341. if !b {
  342. panic("not expected")
  343. }
  344. if newContext, v := p.functions[n]; v {
  345. //am i certain that constraint.inputs is alwazs equal to n??? me dont like it
  346. for i, argument := range constraint.Inputs {
  347. isConst, _ := isValue(argument)
  348. if isConst {
  349. continue
  350. }
  351. isFunc, _, _ := isFunction(argument)
  352. if isFunc {
  353. panic("functions as arguments no supported yet")
  354. //p.extendedFunctionRenamer(contextCircuit,)
  355. }
  356. //at this point I assert that argument is a variable. This can become troublesome later
  357. //first we get the circuit in which the argument was created
  358. inputOriginCircuit := p.functions[getContextFromVariable(argument)]
  359. //we pick the gate that has the argument as output
  360. if gate, ex := inputOriginCircuit.gateMap[argument]; ex {
  361. //we pick the old circuit inputs and let them now reference the same as the argument gate did,
  362. oldGate := newContext.gateMap[newContext.Inputs[i]]
  363. //we take the old gate which was nothing but a input
  364. //and link this input to its constituents coming from the calling contextCircuit.
  365. //i think this is pretty neat
  366. oldGate.value = gate.value
  367. oldGate.right = gate.right
  368. oldGate.left = gate.left
  369. } else {
  370. panic("not expected")
  371. }
  372. }
  373. //newContext.renameInputs(constraint.Inputs)
  374. return newContext
  375. }
  376. return nil
  377. }
  378. func NewProgram() (p *Program) {
  379. p = &Program{
  380. functions: map[string]*Circuit{},
  381. globalInputs: []string{"one"},
  382. arithmeticEnvironment: prepareUtils(),
  383. }
  384. return
  385. }
  386. // GenerateR1CS generates the R1CS polynomials from the Circuit
  387. func (p *Program) GenerateReducedR1CS(mGates []gate) (r1CS R1CS) {
  388. // from flat code to R1CS
  389. offset := len(p.globalInputs)
  390. // one + in1 +in2+... + gate1 + gate2 .. + out
  391. size := offset + len(mGates)
  392. indexMap := make(map[string]int)
  393. for i, v := range p.globalInputs {
  394. indexMap[v] = i
  395. }
  396. for i, v := range mGates {
  397. indexMap[v.value.Out] = i + offset
  398. }
  399. for _, g := range mGates {
  400. if g.OperationType() == MULTIPLY {
  401. aConstraint := r1csqap.ArrayOfBigZeros(size)
  402. bConstraint := r1csqap.ArrayOfBigZeros(size)
  403. cConstraint := r1csqap.ArrayOfBigZeros(size)
  404. insertValue := func(val factor, arr []*big.Int) {
  405. if val.typ != CONST {
  406. if _, ex := indexMap[val.name]; !ex {
  407. panic(fmt.Sprintf("%v index not found!!!", val.name))
  408. }
  409. }
  410. value := new(big.Int).Add(new(big.Int), fractionToField(val.multiplicative))
  411. if val.negate {
  412. value.Neg(value)
  413. }
  414. //not that index is 0 if its a constant, since 0 is the map default if no entry was found
  415. arr[indexMap[val.name]] = value
  416. }
  417. for _, val := range g.leftIns {
  418. insertValue(val, aConstraint)
  419. }
  420. for _, val := range g.rightIns {
  421. insertValue(val, bConstraint)
  422. }
  423. cConstraint[indexMap[g.value.Out]] = big.NewInt(int64(1))
  424. if g.value.invert {
  425. tmp := aConstraint
  426. aConstraint = cConstraint
  427. cConstraint = tmp
  428. }
  429. r1CS.A = append(r1CS.A, aConstraint)
  430. r1CS.B = append(r1CS.B, bConstraint)
  431. r1CS.C = append(r1CS.C, cConstraint)
  432. } else {
  433. panic("not a m gate")
  434. }
  435. }
  436. return
  437. }
  438. var Utils = prepareUtils()
  439. func fractionToField(in [2]int) *big.Int {
  440. return Utils.FqR.Mul(big.NewInt(int64(in[0])), Utils.FqR.Inverse(big.NewInt(int64(in[1]))))
  441. }
  442. //Calculates the witness (program trace) given some input
  443. //asserts that R1CS has been computed and is stored in the program p memory calling this function
  444. func CalculateWitness(input []*big.Int, r1cs R1CS) (witness []*big.Int) {
  445. witness = r1csqap.ArrayOfBigZeros(len(r1cs.A[0]))
  446. set := make([]bool, len(witness))
  447. witness[0] = big.NewInt(int64(1))
  448. set[0] = true
  449. for i := range input {
  450. witness[i+1] = input[i]
  451. set[i+1] = true
  452. }
  453. zero := big.NewInt(int64(0))
  454. for i := 0; i < len(r1cs.A); i++ {
  455. gatesLeftInputs := r1cs.A[i]
  456. gatesRightInputs := r1cs.B[i]
  457. gatesOutputs := r1cs.C[i]
  458. sumLeft := big.NewInt(int64(0))
  459. sumRight := big.NewInt(int64(0))
  460. sumOut := big.NewInt(int64(0))
  461. index := -1
  462. division := false
  463. for j, val := range gatesLeftInputs {
  464. if val.Cmp(zero) != 0 {
  465. if !set[j] {
  466. index = j
  467. division = true
  468. break
  469. }
  470. sumLeft.Add(sumLeft, new(big.Int).Mul(val, witness[j]))
  471. }
  472. }
  473. for j, val := range gatesRightInputs {
  474. if val.Cmp(zero) != 0 {
  475. sumRight.Add(sumRight, new(big.Int).Mul(val, witness[j]))
  476. }
  477. }
  478. for j, val := range gatesOutputs {
  479. if val.Cmp(zero) != 0 {
  480. if !set[j] {
  481. if index != -1 {
  482. panic("invalid R1CS form")
  483. }
  484. index = j
  485. break
  486. }
  487. sumOut.Add(sumOut, new(big.Int).Mul(val, witness[j]))
  488. }
  489. }
  490. if !division {
  491. set[index] = true
  492. witness[index] = new(big.Int).Mul(sumLeft, sumRight)
  493. } else {
  494. b := sumRight.Int64()
  495. c := sumOut.Int64()
  496. set[index] = true
  497. //TODO replace with proper multiplication of b^-1 within the finite field
  498. witness[index] = big.NewInt(c / b)
  499. //Utils.FqR.Mul(sumOut, Utils.FqR.Inverse(sumRight))
  500. }
  501. }
  502. return
  503. }
  504. var hasher = sha256.New()
  505. func hashTogether(a, b []byte) []byte {
  506. hasher.Reset()
  507. hasher.Write(a)
  508. hasher.Write(b)
  509. return hasher.Sum(nil)
  510. }