When Sealos meets blockchain

When Sealos meets blockchain

Using blockchain technology does not necessarily mean issuing coins. Many business systems are also suitable for using these technologies, such as a unified payment system, a points system, etc., which can be used as a company's financial infrastructure or payment center. There are many benefits to using chain technology:

  • High availability, built-in multi-region high consistency capabilities, built-in high availability capabilities and verification capabilities.
  • It is safe and prevents hackers or users from tampering with fund accounts to a great extent. It has complete asymmetric encryption capabilities.
  • It has mature payment and transfer capabilities, and only needs to call a few simple interfaces to complete the amount conversion.
  • High robustness, each new region can run a miner node locally, and the local node is responsible for establishing p2p communication with other nodes.
  • Multi-data center data has strong consistency, and there will be no data split due to network problems.
  • Smart contracts can explore more business possibilities and have good scalability.

For example, this is the architecture diagram of a unified payment system based on blockchain technology, which mainly uses blockchain to create a data infrastructure.

This article mainly talks about the implementation details of how to build such a solution. The main core technologies are:

  • The substrate framework is now merged into polkadot-sdk, the bottom layer of the blockchain.
  • sealos is used to start the blockchain in a containerized manner.
  • laf is used to write code to implement user account creation, transfer and other operations.

Start blockchain

Open https://cloud.sealos.ioUsage management

image

image

Command line parameter details:

["--name","sealchain","--chain","/etc/customSpec.json","--rpc-external","--rpc-cors","all"]

The configuration file here is a bit disgusting. You can not add it when you start testing. Just remove the --chain /etc/customSpec.json parameter.

This configuration is generated with the command:

$ substrate build-spec > myCustomSpec.json

There is a system code in this configuration that is very disgusting and very long. It is compiled into wasm code and cannot be deleted. Therefore, this configuration can only be generated first and then the configuration file can be modified. I really don’t agree with this approach of substrate, which leads to editing the configuration. The cost of documentation is very high.

Test connectivity

Enterhttps://laf.dev/ Start an application and write a function. There is no need to teach you this. Just use your IQ and laf You will definitely know the ease of use. Of course, if your time is not valuable, you can also build a node.js environment by yourself. I can ensure that the environment I build will disgust you to death.

image

When the log is output normally, it means that the chain is working normally.

import cloud from '@lafjs/cloud'
const { ApiPromise, WsProvider } = require('@polkadot/api');

export default async function (ctx: FunctionContext) {
  const provider = new WsProvider('wss://mlnqtutcpqcy.cloud.sealos.io');
  const api = await ApiPromise.create({ provider });

  const chain = await api.rpc.system.chain();
  const lastHeader = await api.rpc.chain.getHeader();

  console.log(`Connected to chain ${chain} and block number ${lastHeader.number}`);
}

Create an account (Keyring)

import cloud from '@lafjs/cloud'
import { Keyring } from '@polkadot/keyring';
import { mnemonicGenerate } from '@polkadot/util-crypto';

export default async function (ctx: FunctionContext) {
  // 生成一个新的 12 个单词的助记词
  const mnemonic: string = mnemonicGenerate(12);
  console.log(`Mnemonic: ${mnemonic}`);

  // 创建一个新的 keyring
  const keyring = new Keyring({ type: 'sr25519' });

  // 从助记词创建一个新的账户
  const pair = keyring.addFromMnemonic(mnemonic);
  console.log(`Address: ${pair.address}`);
}

There is no need to connect to the chain here. Essentially, the user's account is the public key, and the public and private keys are usually difficult to remember, and it is easy to misunderstand the capitalization, such as 0 and o, 1 and l, so people are very smart to figure it out. After using the mnemonic phrase, a key pair is generated based on 12 common words. Now it is easy to remember. So your mnemonic phrase is everything to you. Don’t let others know it, similar to this:

unhappy enforce oil ridge zebra pupil razor worth polar inform enter bomb

The address looks like this:

5HjoX44CVrqTpVLqYtiF2cFSmDwtbNUfrbKcEbKDyLnP8NCv

Next we can transfer money from the super account to this account, and then check the funds in this account.

transfer

For convenience, let’s encapsulate the API a little bit

import { ApiPromise, WsProvider, Keyring } from '@polkadot/api'
// 连接到你的Polkadot节点
const provider = new WsProvider('wss://mlnqtutcpqcy.cloud.sealos.io');
let api = null

export async function getAPI() {
  if(!api) {
    api = await ApiPromise.create({ provider });
  }

  return api
}

Transfer money from super account

import cloud from '@lafjs/cloud'
import { ApiPromise, Keyring } from '@polkadot/api'
import { getAPI } from '@/api'

export default async function (ctx: FunctionContext) {

  const api = await getAPI()

  // 创建一个新的Keyring实例,并添加Alice账户
  const keyring = new Keyring({ type: 'sr25519' });
  // 超级账户的私钥
  const alicePair = keyring.addFromUri('slender alter hybrid catalog feature video pumpkin random sniff advice spoil apple');  // Alice的助记词

  // 你的接收者地址和转账金额
  const recipientAddress = '5HjoX44CVrqTpVLqYtiF2cFSmDwtbNUfrbKcEbKDyLnP8NCv';  // 替换为你的接收者地址
  const amount = 1024000000000;  // 替换为你要转账的金额

  // 查询Alice账户的余额
  const { data: balance } = await api.query.system.account(alicePair.address);

  console.log(`Alice's balance is ${balance.free}`);

  // 创建并发送转账交易
  const transfer = api.tx.balances.transferAllowDeath(recipientAddress, amount);
  const hash = await transfer.signAndSend(alicePair, { nonce: 6});

  console.log(`Transfer sent with hash ${hash.toHex()}`);
}

Then check to see if the money has been received in the account:

import cloud from '@lafjs/cloud'
import { ApiPromise, Keyring } from '@polkadot/api'
import { getAPI } from '@/api'

export default async function (ctx: FunctionContext) {
  const api = await getAPI()

  // 查询Alice账户的余额
  const { data: balance } = await api.query.system.account('5HjoX44CVrqTpVLqYtiF2cFSmDwtbNUfrbKcEbKDyLnP8NCv');

  console.log(`Alice's balance is ${balance.free}`);
}

At this point, you have learned to start a blockchain on sealos, and use laf to perform some basic development and chain interaction. I wish you all a happy sewing machine in the future. Here’s something more advanced.

Chain super administrator configuration

The super administrator's money is obtained from the substrate's genesis, which is the configuration file of the genesis block:

{
  "name": "Sealchain",
  "id": "sealos_net",
  "chainType": "Live",
  "bootNodes": [
    ],
  "telemetryEndpoints": null,
  "protocolId": null,
  "properties": null,
  "codeSubstitutes": {},
  "genesis": {
    "runtime": {
      "system": {
        "code": 275debf565db8f5318502....980e6412a472c0af5e652d25fa9838a78d0a8449688794d7749638feb6b93e0191ac90b07516"
      },
      "aura": {
        "authorities": [
          "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
          "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
        ]
      },
      "grandpa": {
        "authorities": [
          [
            "5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu",
            1
          ],
          [
            "5GoNkf6WdbxCFnPdAnYYQyCjAKPJgLNxXwPjwTh6DGg6gN3E",
            1
          ]
        ]
      },
      "balances": {
        "balances": [
          [
            "5Gh3LUk21PtfZMTnQRZDqGDVwD2mozQdwHyKRj6PW6n9r65C",
            1152921504606846976
          ],

          [
            "5CRmqmsiNFExV6VbdmPJViVxrWmkaXXvBrSX8oqBT8R9vmWk",
            1152921504606846976
          ]
        ]
      },
      "transactionPayment": {
        "multiplier": "1000000000000000000"
      },
      "sudo": {
        "key": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"
      }
    }
  }
}

You must not copy and paste this file, because the runtime.system.code field inside is the compiled wasm, so you must use the command to generate this file and modify it based on this file. I was fooled by this problem.

Then the balances field can be used to configure the funds in the initial address. This address can be generated with the above code. You can keep the private key yourself without touching the Internet. It is very simple to configure and I wish you all financial freedom.

image

Then add a new configuration in sealos and specify the configuration file on the command line.

Build your own chain of container images

There is an environment for compiling rust

https://docs.substrate.io/tutorials/build-a-blockchain/build-local-blockchain/
git clone https://github.com/substrate-developer-hub/substrate-node-template
cargo build --release
FROM ubuntu:23.10
RUN apt update && apt install --assume-yes git clang curl libssl-dev protobuf-compiler && rm -rf /var/lib/apt/lists/*
COPY ./target/release/node-template .
CMD ./node-template --dev

[Friendly reminder: Moving bricks is risky, so be careful when running. If you step on a sewing machine, your loved ones will burst into tears] sealos is a cloud operating system distribution with kubernetes as the core, allowing Cloud native is simple and popular

laf Writing code is as easy as writing a blog. I don’t care about docker or kubernetes. I only care about writing business!

Guess you like

Origin blog.csdn.net/github_35614077/article/details/134919804