1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | func NonDeterministicFunction(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { fmt.Println("Entering NonDeterministicFunction") //Use random number generator to generate the ID var random = rand.New(rand.NewSource(time.Now().UnixNano())) var loanApplicationID = "la1" + strconv.Itoa(random.Intn(1000)) var loanApplication = args[0] var la LoanApplication err := json.Unmarshal([]byte(loanApplication), &la) if err != nil { fmt.Println("Could not unmarshal loan application", err) return nil, err } la.ID = loanApplicationID laBytes, err := json.Marshal(&la) if err != nil { fmt.Println("Could not marshal loan application", err) return nil, err } err = stub.PutState(loanApplicationID, laBytes) if err != nil { fmt.Println("Could not save loan application to ledger", err) return nil, err } fmt.Println("Successfully saved loan application") return []byte(loanApplicationID), nil } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | func TestNonDeterministicFunction(t *testing.T) { fmt.Println("Entering TestNonDeterministicFunction") attributes := make(map[string][]byte) const peerSize = 4 var stubs [peerSize]*shim.CustomMockStub var responses [peerSize][]byte var loanApplicationCustom = `{"propertyId":"prop1","landId":"land1","permitId":"permit1","buyerId":"vojha24","personalInfo":{"firstname":"Varun","lastname":"Ojha","dob":"dob","email":"varun@gmail.com","mobile":"99999999"},"financialInfo":{"monthlySalary":16000,"otherExpenditure":0,"monthlyRent":4150,"monthlyLoanPayment":4000},"status":"Submitted","requestedAmount":40000,"fairMarketValue":58000,"approvedAmount":40000,"reviewedBy":"bond","lastModifiedDate":"21/09/2016 2:30pm"}` //Simulate execution of the chaincode function by multiple peers on their local ledgers for j := 0; j < peerSize; j++ { stub := shim.NewCustomMockStub("mockStub", new(SampleChaincode), attributes) if stub == nil { t.Fatalf("MockStub creation failed") } stub.MockTransactionStart("tx" + string(j)) resp, err := NonDeterministicFunction(stub, []string{loanApplicationCustom}) if err != nil { t.Fatalf("Could not execute NonDeterministicFunction ") } stub.MockTransactionEnd("tx" + string(j)) stubs[j] = stub responses[j] = resp } for i := 0; i < peerSize; i++ { if i < (peerSize - 1) { la1Bytes, _ := stubs.GetState(string(responses)) la2Bytes, _ := stubs[i+1].GetState(string(responses[i+1])) la1 := string(la1Bytes) la2 := string(la2Bytes) if la1 != la2 { //TODO: Compare individual values to find mismatch t.Fatalf("Expected all loan applications to be identical. Non Deterministic chaincode error") } } //All loan applications retrieved from each of the peer's ledger's match. Function is deterministic } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |