[Everyone’s Blockchain] Chatbot with Blockchain (feat. AI Network Blockchain)

AI Network
AI Network
Published in
9 min readSep 29, 2021

With the recent boom in cryptocurrency investment, such as Bitcoin, you might have heard the word blockchain a lot. But, what is blockchain?

The dictionary definition of blockchain is read as follows.

“A kind of distributed data storage technology that transparently records transaction details in a digital ledger that anyone can view, and copies and stores them on multiple computers”.

Put simply, a blockchain is a decentralized database. This database records its contents through the following procedure:

  1. Some transactions, which are considered as units of work performed to change the state of the database, are wrapped in one block.
  2. Then, a hash function that converts the transaction contents in a block into a fixed-length string is used to create a single hash value as shown in the figure below.
https://www.euromoney.com/learning/blockchain-explained/how-blockchain-data-is-stored-and-secured

3. After that, a new hash value is created by using the hash value obtained in step 2 for the hash value of the previous block. Then, the string created in this step becomes the hash value of this block, and the hash value of the previous block and the newly obtained hash value are stored together in the block.

In this way, each block has the hash value of the previous block as if the blocks are connected in a chain form, hence the name blockchain.

Blockchain has the following two main characteristics.

  • Decentralization
https://www.researchgate.net/publication/335749445_How_and_Why_Artificial_Intelligence_Mixed_Reality_and_Blockchain_Technologies_Will_Change_Marketing_We_Know_Today

In the past, most databases had a central server, and the computer server managed requests from clients or the database in general. However, blockchain uses a peer-to-peer (P2P) network rather than a client-server network.

In simple terms, a P2P network is a two-way file transfer system that connects computers to each other and sends as well as receives files without a central server. In blockchain, each computer that is part of this network is called a node.

https://cyberfrat.com/is-the-blockchain-an-economy-or-a-computer-science-innovation/

As shown in the image above, each node contains a copy of the entire record of data stored in the blockchain. If a user wants to arbitrarily change the information stored in the blockchain, the majority of other nodes must verify the validity of the change based on the data records they have in order to agree to such change. The blockchain is called a decentralized system because each node does what the central server did in the past.

  • Transparency

Thanks to the characteristic of decentralization mentioned above, anyone can have a private node and see all records transparently in real time by replicating the data stored on the blockchain.

A chatbot using blockchain?

Based on its reliability and stability, blockchain is being used not only in cryptocurrency, but also in various fields such as finance, distribution, logistics, manufacturing, and public services. In this article, we will create a chatbot using blockchain technology. Some of you may be wondering why you should use blockchain when you can simply create a chatbot without it.

Let’s think of an application that helps you pay through a chatbot. At first, most people may be reluctant to entrust sensitive financial or personal information, such as credit card information to chatbots. However, if you use a chatbot using blockchain technology, the transaction history will be recorded on a distributed database that can be viewed by anyone, so customers can feel relieved that their personal information has been used diligently by looking at the successful transaction history.

In this way, applying blockchain technology to chatbots increases security and transparency, so it may be capable to gain higher levels of trust from users.

Let’s create a chatbot using blockchain

AI Network Blockchain

In this tutorial, we will use AI Network Blockchain developed by Common Computer, hereinafter referred to as AIN Blockchain. AI Network blockchain has been designed to process large transactions and to securely record communications between clients sending requests and nodes processing operations. More information on AIN Blockchain can be found here.

The reason why we use AIN Blockchain in this tutorial is that the transaction fee is free. Commonly used blockchains such as Bitcoin charge transaction fees. In other words, you have to pay a certain amount of money (in this case, Bitcoin) to add new transaction details on the blockchain, such as transferring Bitcoin. This fee is then distributed to miners who verify the transaction details. AIN Blockchain allows to record transactions without fees so many developers can have access and use blockchain technology.

Test it out

Now, let’s implement a simple chatbot by referring to the guidelines of the AIN official documentation.

Requirement

  • Node.js

1. Install ain-js

First, you need a JavaScript SDK called Ain-js to send a transaction request to AIN blockchain and receive a response.

Enter the following command to install ain-js.

In this tutorial, ain-js version 1.1.8 was used.

npm install @ainblockchain/ain-js

2. Create an AIN account

You can create an account with the code below. Chain ID must be set to 1 to use ain-js on the Mainnet. (0: Testnet, 1: Mainnet)

const Ain = require('@ainblockchain/ain-js').default;
// If you want to use the mainnet, set Chain ID to 1.
// const ain = new Ain('https://mainnet-api.ainetwork.ai', 1);
const ain = new Ain('https://testnet-api.ainetwork.ai', 0);
const accounts = ain.wallet.create(1);
const myAddress = accounts[0];
// Set myAddress as the default account
ain.wallet.setDefaultAccount(myAddress);
// Print defaultAccount (Need to backup your private key)
console.log(ain.wallet.defaultAccount);

After saving the above code as a createAccount.js file, run it through the command node createAccount.js, and you can see the output below in the terminal window.

{
address: $your_address,
private_key: $your_private_key,
public_key: $your_public_key
}

We’re going to keep using the address and private key above, so please record it somewhere!

3. Get AIN

As mentioned above, in the AIN Blockchain, you can record transactions for free. So, you can skip this step in this tutorial!

However, since free users have limitations in bandwidth usage, etc., they have to pay certain amount of transaction fee in AIN in order to make an actual serviceable app, not for development. Go here to get 100 AIN for testing.

Please put the address obtained in step 2 as below.

You can check the received AIN here. If you enter the address obtained from step2 in the search bar, you can see that 100AIN has been deposited as below.

4. Create an app

You can create a simple app with the code below.

const Ain = require('@ainblockchain/ain-js').default;
// If you want to use the mainnet, set Chain ID to 1.
// const ain = new Ain('https://mainnet-api.ainetwork.ai', 1);
const ain = new Ain('https://testnet-api.ainetwork.ai', 0);
ain.wallet.addAndSetDefaultAccount(privateKey); // Use your own private key from Step 2
const myAddress = ain.wallet.defaultAccount.address;
const appName = 'my_bot'; // Use your own app name!ain.db.ref(`/manage_app/${appName}/create/${Date.now()}`).setValue({
value: {
admin: {
[myAddress]: true,
},
},
nonce: -1,
})
.then((res) => {
console.log(`res: ${JSON.stringify(res)}`);
});

Just save the above code as a createApp.js file and run it through the command node createApp.js and you are done! That's easy, right?

The newly created app can be checked through the code below.

const appName = 'my_bot'; // Use your own app name!
const appPath = `/apps/${appName}`;
ain.db.ref(appPath).getOwner()
.then(res => {
console.log(JSON.stringify(res, null, 2));
});

If the app is successfully created, you will get the following result when you run the above code.

{
".owner": {
"owners": {
"<your-address>": {
"branch_owner": true,
"write_function": true,
"write_owner": true,
"write_rule": true
}
}
}
}

5. Connect to echo-bot trigger

Now it’s time to connect a very simple chatbot known as “echo-bot”. Two simple steps are required for this.

First, connect the echo-bot trigger function using the setFunction function, which is ain-js built-in function.

At this point, when you send a message, echo-bot will not respond. Because the default rule is set as shown below, echo-bot cannot record the answer in the database.

{
".rule": {
"write": "auth.addr === '<your-address>'"
}
}

So, the next thing to do is to set a rule so that the echo-bot trigger can record the response in the database.

  • Connect to echo-bot trigger
const appName = 'my_bot'; // Use your own name
const appPath = `/apps/${appName}`;
const functionPath = `${appPath}/messages/$user_addr/$timestamp/user`; // Wild cards!
ain.db.ref(functionPath).setFunction({
value: {
'.function': {
'my-bot-trigger': { // Use your own function id
function_type: 'REST',
function_url: '<http://echo-bot.ainetwork.ai/trigger>',
function_id: 'my-bot-trigger',
},
},
},
nonce: -1,
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
});
  • Set rule
const appName = 'my_bot'; // Use your own name
const appPath = `/apps/${appName}`;

const echobotRulePath = `${appPath}/messages/$user_address/$timestamp/echo-bot`

ain.db.ref(echobotRulePath).setRule({
value: {
'.rule': {
'write': true,
},
},
nonce: -1,
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
});

The above two processes can be summarized in one code as follows.

const Ain = require('@ainblockchain/ain-js').default;
// If you want to use the mainnet, set Chain ID to 1.
// const ain = new Ain('https://mainnet-api.ainetwork.ai', 1);
const ain = new Ain('https://testnet-api.ainetwork.ai', 0);
ain.wallet.addAndSetDefaultAccount(privateKey); // Use your own private key from Step 2
const appName = 'my_bot'; // Use your own name
const appPath = `/apps/${appName}`;
const functionPath = `${appPath}/messages/$user_addr/$timestamp/user`; // Wild cards!
ain.db.ref(functionPath).setFunction({
value: {
'.function': {
'my-bot-trigger': { // Use your own function id
function_type: 'REST',
function_url: '<http://echo-bot.ainetwork.ai/trigger>',
function_id: 'my-bot-trigger',
},
},
},
nonce: -1,
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
});
const echobotRulePath = `${appPath}/messages/$user_address/$timestamp/echo-bot` // Wild cards!ain.db.ref(echobotRulePath).setRule({
value: {
'.rule': {
'write': true,
},
},
nonce: -1,
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
});

Save the above code as setChatbot.js file and run it through the command node setChatbot.js, then, the trigger setting is finished!

6. Send a message

Now, just send a message and check if you get a response from the echo-bot!

Caution: The echo-bot trigger server can go down at any time, so even if you set it up properly, there may be no response!

You can send a message using the code below.

const Ain = require('@ainblockchain/ain-js').default;
// If you want to use the mainnet, set Chain ID to 1.
// const ain = new Ain('https://mainnet-api.ainetwork.ai', 1);
const ain = new Ain('https://testnet-api.ainetwork.ai', 0);
ain.wallet.addAndSetDefaultAccount(privateKey); // Use your own private key from Step 2
const appName = 'my_bot'; // Use your own name
const appPath = `/apps/${appName}`;
const valuePath = `${appPath}/messages/${ain.wallet.defaultAccount.address}/${Date.now()}/user`;
ain.db.ref(valuePath).setValue({
value: 'Hello!',
nonce: -1,
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
});

You can check the message sent above and the response of echo-bot at the address below.

<https://insight.ainetwork.ai/database/values/apps/${your_app_name}/messages/${your_address}>

Use of Blockchain

Although blockchain technology has become widely known thanks to Bitcoin, it is important to know that not only can it be used in Bitcoin, but also in finance, insurance, transportation, healthcare, energy, logistics and delivery, music, manufacturing, IoT, social media, and public sectors, amongst others. It can be used as a reliable database in various fields.

Of course, at this time, the blockchain technology has some problems to be improved, such as the fact that is still relatively slow due to the nature of the P2P network, and also, the increase in the accumulated amount of data due to its append-only characteristics. However, when trying to develop reliable applications, using blockchain technology must be a good option.

References

  1. Bitcoin Book Github
  2. What is Blockchain
  3. How blockchain data is stored and secured
  4. Why Chatbots Need Blockchain

AI network is a blockchain-based platform and aims to innovate the AI development environment. It represents a global back-end infrastructure with millions of open source projects deployed live.

If you want to know more about us,

--

--

AI Network
AI Network

A decentralized AI development ecosystem built on its own blockchain, AI Network seeks to become the “Internet for AI” in the Web3 era.