The event chain is a microledger. Normally a ledger is a hash chain of blocks, with each block containing multiple transactions. The event chain is a hash chain of individual events.
Create an event chain
The event id is generated from the account public key and a random value or a nonce, to prevent collisions.
import LTO from '@ltonetwork/lto';
import { EventChain } from '@ltonetwork/lto/events';
const lto = new LTO('T');
const account = lto.account();
const chain = new EventChain(account); // Creates an empty event chain with a valid id
Adding events
The genesis event determines the purpose of the event chain. For an Ownable the genesis event contains an instantiate message.
import { EventChain, Event } from '@ltonetwork/lto/events';
const body = {
'@context': 'instantiate_msg.json',
ownable_id: '88pDRu52FpsU3kKHwdvPV21RMkBqVqNnthjfdCesTHQhLnUpanw49n6b2PzGnEy',
package: 'bafybeie4ts4mbcw4pswzh45bj32ulcyztup2dr7zbbjv3y2ym3q3uuejba',
network_id: 'T',
};
const lto = new LTO('T');
const account = lto.account();
const chain = new EventChain(account);
new Event(body).addTo(chain).signWith(account);
Events need to be added to the chain before they can be signed.
Loading an event chain
You can store or submit an event chain as JSON. To create an event chain object from JSON data use the from method.
When receiving an event chain from an untrusted source, you should always validate it. The validate method checks the integrity of the hash chain and verifies the signatures.
chain.validate();
The validate function does not return any value, but throws an error in case something is wrong with the chain.
Additionally, you may want to check if the signer of the genesis event is the account that created the event chain.
const genesisSigner = lto.account(chain.events[0].signKey);
if (!chain.isCreatedBy(genesisSigner))
throw new Error('Event chain hijacking: genesis event not signed by chain creator');
Partial chain
There are several reasons why you'd only want to get part of the event chain. For instance, you may only need to share added events with another party. To do so you can startingWith or startingAfter method.
The event chain doesn't have an internal consensus mechanism. Instead, it relies on anchoring events on the public chain to determine which branch should be accepted in case of a merge conflict.
Anchoring events
To detect rollbacks, resolve merge conflicts, and prevent tampering, events should be anchored. Anchoring is the action of writing the event hash to the public chain.
For rollback detection, we use mapped anchoring where the event hash is combined with a state.