Share Your AWS re:Post Experience - Quick 3 Question Survey
Help us improve AWS re:Post! We're interested in understanding how you use re:Post and its impact on your AWS journey. Please take a moment to complete our brief 3-question survey.
Getting Started with AMB Access Bitcoin
Learn how to get started with Amazon Managed Blockchain (AMB) Access Bitcoin using JavaScript, Python, or Go
Introduction
This guide shows you how to get started with Amazon Managed Blockchain (AMB) Access Bitcoin. It includes sample code in JavaScript, Python, and Go to retrieve the current block height of Bitcoin Mainnet or Testnet by calling the getblockcount
JSON-RPC method with Signature Version 4 (SigV4) authentication.
Prerequisites
- Installation of the AWS Command Line Interface (CLI).
- Run the command
aws configure
to set the variables for your IAM User’sAccess Key ID
,Secret Access Key
, andRegion
.- Ensure that this User has the appropriate IAM permissions for AMB Access Bitcoin. For this tutorial, you can use the
AmazonManagedBlockchainFullAccess
managed policy.
- Ensure that this User has the appropriate IAM permissions for AMB Access Bitcoin. For this tutorial, you can use the
- Run the command
Step 1: Setting up the project
Create a new directory for your project and change into it by running the following command:
mkdir accessBitcoin && cd accessBitcoin
Step 2: Make a request to the AMB Access Bitcoin endpoint
JavaScript
Prerequisite: Installation of Node.js (version 18 or above). It is recommended to utilize NVM for version management.
- Run the following command to install the necessary dependencies:
npm install axios @aws-sdk/credential-provider-node @aws-sdk/signature-v4 @aws-crypto/sha256-js
Axios
enables HTTP requests, credential-provider-node
retrieves your AWS credentials, signature-v4
adds authentication information to AWS service requests, and sha256-js
generates hashes as part of the request signing process.
- Create a new file (e.g
btc.js
) in the root of your directory and copy the following code:
const axios = require('axios');
const { SignatureV4 } = require('@aws-sdk/signature-v4');
const { Sha256 } = require('@aws-crypto/sha256-js');
const { defaultProvider } = require('@aws-sdk/credential-provider-node');
const region = 'us-east-1'
const sigv4 = new SignatureV4({
credentials: defaultProvider(),
service: 'managedblockchain',
region: region,
sha256: Sha256
});
const rpcRequest = async () => {
// The sample request makes a call to the getblockcount JSON-RPC. To make other calls, modify the rpc object with a different Bitcoin JSON-RPC.
const rpc = JSON.stringify({
jsonrpc: "2.0",
"id": "1001",
method: 'getblockcount',
params: []
});
const network = 'mainnet' // or 'testnet'
const url = new URL(`https://${network}.bitcoin.managedblockchain.${region}.amazonaws.com/`);
try {
const signed = await sigv4.sign({
method: 'POST',
path: url.pathname,
body: rpc,
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip',
host: url.hostname,
},
});
const { data } = await axios({ url, ...signed, data: signed.body });
console.log('AMB Access BTC Response:', data['result']);
return data;
} catch (error) {
console.log('Error:', error.response.data);
}
};
rpcRequest();
- Execute the script by running the following command:
node btc.js
Python
Prerequisites: Installation of Python and the AWS SDK for Python (Boto3).
- Create a new file (e.g
btc.py
) in the root of your directory and copy the following code:
import json
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.session import Session
def signed_rpc_request(method, url, service, region, rpc):
session = Session()
credentials = session.get_credentials()
sigv4 = SigV4Auth(credentials, service, region)
data = json.dumps(rpc)
request = AWSRequest(method=method, url=url, data=data, headers={
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
})
sigv4.add_auth(request)
http_response = requests.post(url, data=data, headers=request.prepare().headers)
return http_response
# Define the parameters
region = 'us-east-1'
service = 'managedblockchain'
network = 'mainnet' # or 'testnet'
url = f'https://{network}.bitcoin.managedblockchain.{region}.amazonaws.com/'
# The sample request makes a call to the getblockcount JSON-RPC. To make other calls, modify the rpc object with a different Bitcoin JSON-RPC.
rpc = {
"jsonrpc": "2.0",
"id": "1001",
"method": "getblockcount",
"params": []
}
# Make the signed RPC request
response = signed_rpc_request('POST', url, service, region, rpc)
# Print the response
print('AMB Access BTC Response: ' + str(response.json()['result']))
- Run the script with the following command:
python btc.py
Go
Prerequisite: Installation of Go
- Initialize your project by running the following command:
go mod init example
- Run the following commands to install necessary dependencies:
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
- Create a new file (e.g
btc.go
) in the root of your directory and copy the following code:
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
func main() {
cfg, err := config.LoadDefaultConfig(context.Background())
if err != nil {
log.Fatalf("Failed retrieving AWS creds: %s", err)
}
// The sample request makes a call to the getblockcount JSON-RPC. To make other calls, modify the rpc object with a different Bitcoin JSON-RPC.
rpcBody, err := json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"id": "1001",
"method": "getblockcount",
"params": []interface{}{},
})
if err != nil {
log.Fatalf("Error marshaling rpc body: %s", err)
}
url := "https://mainnet.bitcoin.managedblockchain.us-east-1.amazonaws.com/"
req, err := http.NewRequest("POST", url, bytes.NewReader(rpcBody))
if err != nil {
log.Fatalf("Error creating request: %s", err)
}
req.Header.Set("Content-Type", "application/json")
hash := sha256.Sum256(rpcBody)
hashHex := hex.EncodeToString(hash[:])
signer := v4.NewSigner()
credentials, err := cfg.Credentials.Retrieve(context.Background())
if err != nil {
log.Fatalf("Error retrieving credentials: %s", err)
}
if err := signer.SignHTTP(context.Background(), credentials, req, hashHex, "managedblockchain", "us-east-1", time.Now()); err != nil {
log.Fatalf("Error signing request: %s", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("HTTP request failed: %s", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Reading response failed: %s", err)
}
log.Printf("AMB Access BTC Response: %s", string(body))
}
- Run the script with the following command:
go run btc.go
Conclusion
This guide provided a foundation for getting started with AMB Access Bitcoin. These code samples allowed you to retrieve the block height by calling the JSON-RPC method, getblockcount
. Please leave a comment below if you have any questions. If you would like to learn more about AMB Access Bitcoin, you can refer to the documentation. Remember to prioritize security, especially with your AWS credentials.
Relevant content
- asked 3 years agolg...
- Accepted Answerasked 3 years agolg...
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 5 months ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 8 months ago