Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How java engineers use spring boot and web3j to build the application of ethernet block chain

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

Java engineers how to use spring boot and web3j to build Ethernet block chain application, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can get something.

Blockchain is one of the latest buzzwords in the IT world. This technology about digital cryptocurrency, together with Bitcoin, constitutes this hot trend. It is a decentralized, immutable block data structure, which is a cryptographic algorithm that can be safely connected and used. Each block in this structure usually contains an encrypted hash of the previous block, a timestamp, and transaction data. The block chain is a peer-to-peer management network and verifies the communication between nodes before each new block is added. This is part of the theory of blockchain. In short, this is a technology that allows us to manage transactions between both parties in a decentralized way. Now, the question is how do we implement it in our system.

So Tai Tai Fong came. This is a decentralized platform provided by Vitarik Buterin that allows you to create development applications through scripting languages. Its idea is derived from bitcoin and driven by a new encrypted digital coin called Ether, or ethernet coin. Today, ethercoin is the second largest encrypted digital currency after bitcoin. The core of Ethernet Square technology is EVM (Ethernet Square Virtual Machine), which can be regarded as similar to Java virtual machine and with a completely decentralized node network. We use web3j library to realize ethernet transaction based on java world. This is a lightweight, responsive, type-safe java and Android library that combines etheric block chain nodes.

1. Local operation

Although there are many articles on blockchain, it is not easy to find a solution in ethernet related web content that describes how to prepare an instance to run ethernet on a local machine. It is worth mentioning that there are generally two most basic clients available: Geth and Parity. It turns out that we can easily run the node locally using the Docker container. By default, the ethernet main network (public chain) that connects the node. Or, you can connect it to the test network or the Rinkeby network. But the best option to start with is to run in development mode with the development parameter set (--dev) and run the command in the Docker container.

The following command starts the Docker container development mode to invoke the Ethernet square RPC API on port 8545.

$docker run-d-- name ethereum-p 8545 rpc-- rpcaddr "0.0.0.0"-- rpcapi= "db,eth,net,web3,personal"-- rpccorsdomain "*"-- dev

When running the container in development mode, the very good news is that there is a large number of Ether on the default test account. In this case, you don't have to mine any Ether to start testing. It's awesome! Now, let's create some other test accounts and do some checks. To achieve this, we need to run Geth's interactive JavaScript console inside the container.

$docker exec-it ethereum geth attach ipc:/tmp/geth.ipc2. Ethernet Fong nodes are managed using the JavaScript console

Running the JavaScript console makes it easy to display the default account (Coinbase), a list of all available accounts and their balances. The screen here shows my ethernet results.

Now, we must create some test accounts. We can do this by calling the personal.newAccount (password) function. After creating the necessary accounts, we can use the JavaScript console to perform some test transactions and transfer some funds from the base account to the newly created account. Here are the commands for creating accounts and executing transactions.

3. System architecture

The architecture of our demo system is very simple. You don't have to think about complicated things, just tell you how to send transactions to geth nodes and receive transaction receipts. Transaction-service sends new transactions to the Ethernet Fong node, and the bonus-service node listens for incoming transactions. The sender's account then receives a bonus (bonus) for every 10 transactions. The chart here shows a system architecture of our demo.

4.spring boot applications use web3j

I think now we know exactly what we want to do. So, let's implement it. First, we should include all the necessary dependencies so that we can use the web3j library in our Spring boot application. Fortunately, there is a starter available.

Org.web3j web3j-spring-boot-starter 1.6.0

Because we run the Ethernet Fong client in the Docker container, we need to change the web3j call address of the client's automatic default configuration.

Spring: application: name: transaction-serviceserver: port: ${PORT:8090} web3j: client-address: http://192.168.99.100:85455. Build application

If we include web3j starter in our project dependencies, we need to automate the loading of web3j bean. Web3j is responsible for sending the transaction to the Geth client node. It receives the response with a transaction hash, either accepted by the node or rejected due to an error. When creating a transaction object, it is important to set the minimum gas limit to 21000. If you send a lower value, you may receive an error message: intrinsic gas too low.

@ Servicepublic class BlockchainService {private static final Logger LOGGER = LoggerFactory.getLogger (BlockchainService.class); @ Autowired Web3j web3j; public BlockchainTransaction process (BlockchainTransaction trx) throws IOException {EthAccounts accounts = web3j.ethAccounts () .send (); EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount (accounts.getAccounts () .get (trx.getFromId ()), DefaultBlockParameterName.LATEST) .send () Transaction transaction = Transaction.createEtherTransaction (accounts.getAccounts (). Get (trx.getFromId ()), transactionCount.getTransactionCount (), BigInteger.valueOf (trx.getValue ()), BigInteger.valueOf (21000000), accounts.getAccounts (). Get (trx.getToId ()), BigInteger.valueOf (trx.getValue ()); EthSendTransaction response = web3j.ethSendTransaction (transaction). Send (); if (response.getError ()! = null) {trx.setAccepted (false) Return trx;} trx.setAccepted (true); String txHash = response.getTransactionHash (); LOGGER.info ("Tx hash: {}", txHash); trx.setId (txHash); EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt (txHash). Send () If (receipt.getTransactionReceipt (). IsPresent ()) {LOGGER.info ("Tx receipt: {}", receipt.getTransactionReceipt (). Get (). GetCumulativeGasUsed (). IntValue ());} return trx;}}

@ Service is called by the controller from the above code. The POST method requires a BlockchainTransaction object as a parameter. You can send the sender ID, the recipient ID and the transaction amount. The sender and receiver ID can be queried through eth.account [index].

RestControllerpublic class BlockchainController {@ Autowired BlockchainService service; @ PostMapping ("/ transaction") public BlockchainTransaction execute (@ RequestBody BlockchainTransaction transaction) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CipherException, IOException {return service.process (transaction);}}

You can use the following command to call the POST method to send the test transaction.

You should unlock the sender account before sending any transactions.

$curl-- header "Content-Type: application/json"-- request POST-- data'{"fromId": 2, "toId": 1, "value": 3} 'http://localhost:8090/transaction

The application bonus-service listens for transactions processed by the Ethernet Fong node. It calls web3j.transactionObservable (). Subscribe (...) Method to subscribe to notification messages from the web3j library. It will return every 10 transactions from that address and send it to the sender's account once. The following is the implementation of the listenable method in bonus-service.

@ AutowiredWeb3j web3j; @ PostConstructpublic void listen () {Subscription subscription = web3j.transactionObservable (). Subscribe (tx-> {LOGGER.info ("New tx: id= {}, block= {}, from= {}, to= {}, value= {}", tx.getHash (), tx.getBlockHash (), tx.getFrom (), tx.getTo (), tx.getValue (). IntValue ()); try {EthCoinbase coinbase = web3j.ethCoinbase (). Send () EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount (tx.getFrom (), DefaultBlockParameterName.LATEST). Send (); LOGGER.info ("Tx count: {}", transactionCount.getTransactionCount (). IntValue ()); if (transactionCount.getTransactionCount (). IntValue ()% 10 = 0) {EthGetTransactionCount tc = web3j.ethGetTransactionCount (coinbase.getAddress (), DefaultBlockParameterName.LATEST) .send () Transaction transaction = Transaction.createEtherTransaction (coinbase.getAddress (), tc.getTransactionCount (), tx.getValue (), BigInteger.valueOf (2100000), tx.getFrom (), tx.getValue ()); web3j.ethSendTransaction (transaction). Send ();}} catch (IOException e) {LOGGER.error ("Error getting transactions", e);}}) LOGGER.info ("Subscribed")

Blockchain and digital currency are not easy topics to start. By providing a complete scripting language, Etay Fang simplifies the difficulty of using blockchain for application development. Using the docker container images of web3j, spring boot and Ethernet Square geth clients, you can quickly start the solution and realize the local development of blockchain technology.

If you want to clone my library for local development, you can download the source code on github.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report