Exemple #1
0
// PutBlock inserts a raw block into the blockchain at the specified index, nearly no error checking is performed
func (h *Helper) PutBlock(blockNumber uint64, block *pb.Block) error {
	ledger, err := ledger.GetLedger()
	if err != nil {
		return fmt.Errorf("Failed to get the ledger :%v", err)
	}
	return ledger.PutRawBlock(block, blockNumber)
}
Exemple #2
0
func TestServerOpenchainREST_API_GetBlockByNumber(t *testing.T) {
	// Construct a ledger with 0 blocks.
	ledger := ledger.InitTestLedger(t)

	initGlobalServerOpenchain(t)

	// Start the HTTP REST test server
	httpServer := httptest.NewServer(buildOpenchainRESTRouter())
	defer httpServer.Close()

	body := performHTTPGet(t, httpServer.URL+"/chain/blocks/0")
	res := parseRESTResult(t, body)
	if res.Error == "" {
		t.Errorf("Expected an error when retrieving block 0 of an empty blockchain, but got none")
	}

	// add 3 blocks to the ledger
	buildTestLedger1(ledger, t)

	// Retrieve the first block from the blockchain (block number = 0)
	body0 := performHTTPGet(t, httpServer.URL+"/chain/blocks/0")
	var block0 protos.Block
	err := json.Unmarshal(body0, &block0)
	if err != nil {
		t.Fatalf("Invalid JSON response: %v", err)
	}

	// Retrieve the 3rd block from the blockchain (block number = 2)
	body2 := performHTTPGet(t, httpServer.URL+"/chain/blocks/2")
	var block2 protos.Block
	err = json.Unmarshal(body2, &block2)
	if err != nil {
		t.Fatalf("Invalid JSON response: %v", err)
	}
	if len(block2.Transactions) != 2 {
		t.Errorf("Expected block to contain 2 transactions but got %v", len(block2.Transactions))
	}

	// Retrieve the 5th block from the blockchain (block number = 4), which
	// should fail because the ledger has only 3 blocks.
	body4 := performHTTPGet(t, httpServer.URL+"/chain/blocks/4")
	res4 := parseRESTResult(t, body4)
	if res4.Error == "" {
		t.Errorf("Expected an error when retrieving non-existing block, but got none")
	}

	// Illegal block number
	body = performHTTPGet(t, httpServer.URL+"/chain/blocks/NOT_A_NUMBER")
	res = parseRESTResult(t, body)
	if res.Error == "" {
		t.Errorf("Expected an error when URL doesn't have a number, but got none")
	}

	// Add a fake block number 9 and try to fetch non-existing block 6
	ledger.PutRawBlock(&block0, 9)
	body = performHTTPGet(t, httpServer.URL+"/chain/blocks/6")
	res = parseRESTResult(t, body)
	if res.Error == "" {
		t.Errorf("Expected an error when block doesn't exist, but got none")
	}
}