github.com/consensys/gnark@v0.11.0/constraint/r1cs_sparse_test.go (about)

     1  package constraint_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/consensys/gnark/constraint"
     7  	cs "github.com/consensys/gnark/constraint/bn254"
     8  )
     9  
    10  func ExampleSparseR1CS_GetSparseR1Cs() {
    11  	// build a constraint system; this is (usually) done by the frontend package
    12  	// for this Example we want to manipulate the constraints and output a string representation
    13  	// and build the linear expressions "manually".
    14  	// note: R1CS apis are more mature; SparseR1CS apis are going to change in the next release(s).
    15  	scs := cs.NewSparseR1CS(0)
    16  	blueprint := scs.AddBlueprint(&constraint.BlueprintGenericSparseR1C{})
    17  
    18  	Y := scs.AddPublicVariable("Y")
    19  	X := scs.AddSecretVariable("X")
    20  
    21  	v0 := scs.AddInternalVariable() // X²
    22  
    23  	// coefficients
    24  	cOne := scs.FromInterface(1)
    25  	cFive := scs.FromInterface(5)
    26  
    27  	// X² == X * X
    28  	scs.AddSparseR1C(constraint.SparseR1C{
    29  		XA: uint32(X),
    30  		XB: uint32(X),
    31  		XC: uint32(v0),
    32  		QO: constraint.CoeffIdMinusOne,
    33  		QM: constraint.CoeffIdOne,
    34  	}, blueprint)
    35  
    36  	// X² + 5X + 5 == Y
    37  	scs.AddSparseR1C(constraint.SparseR1C{
    38  		XA: uint32(X),
    39  		XB: uint32(v0),
    40  		XC: uint32(Y),
    41  		QO: constraint.CoeffIdMinusOne,
    42  		QL: scs.AddCoeff(cFive),
    43  		QR: scs.AddCoeff(cOne),
    44  		QC: scs.AddCoeff(cFive),
    45  	}, blueprint)
    46  
    47  	// get the constraints
    48  	constraints := scs.GetSparseR1Cs()
    49  
    50  	for _, c := range constraints {
    51  		fmt.Println(c.String(scs))
    52  		// for more granularity use constraint.NewStringBuilder(r) that embeds a string.Builder
    53  		// and has WriteLinearExpression and WriteTerm methods.
    54  	}
    55  
    56  	// Output:
    57  	// 0 + 0 + -1⋅v0 + 1⋅(X×X) + 0 == 0
    58  	// 5⋅X + v0 + -1⋅Y + 5 == 0
    59  }