logo

Parallel Execution

ACS2 - Parallel Execution Standard#

ACS2 helps with parallel transaction execution.

Interface#

Contracts using ACS2 need to implement one method:

Methods#

Method NameRequest TypeResponse TypeDescription
GetResourceInfoaelf.Transactionacs2.ResourceInfoGets the resource info that the transaction execution depends on.

Types#

acs2.ResourceInfo

FieldTypeDescription
write_pathsaelf.ScopedStatePathState paths for writing.
read_pathsaelf.ScopedStatePathState paths for reading.
non_parallelizableboolIf the transaction isn't parallel.

aelf.Address

FieldTypeDescription
valuebytes

aelf.BinaryMerkleTree

FieldTypeDescription
nodesHashLeaf nodes.
rootHashRoot node hash.
leaf_countint32Count of leaf nodes.

aelf.Hash

FieldTypeDescription
valuebytes

aelf.LogEvent

FieldTypeDescription
addressAddressContract address.
namestringLog event name.
indexedbytesIndexed data.
non_indexedbytesNon-indexed data.

aelf.MerklePath

FieldTypeDescription
merkle_path_nodesMerklePathNodeMerkle path nodes.

aelf.MerklePathNode

FieldTypeDescription
hashHashNode hash.
is_left_child_nodeboolIf it's a left child node.

aelf.SInt32Value

FieldTypeDescription
valuesint32

aelf.SInt64Value

FieldTypeDescription
valuesint64

aelf.ScopedStatePath

FieldTypeDescription
addressAddressContract address.
pathStatePathPath of contract state.

aelf.SmartContractRegistration

FieldTypeDescription
categorysint32Contract code category (0: C#).
codebytesContract code byte array.
code_hashHashContract code hash.
is_system_contractboolIf it's a system contract.
versionint32Current contract version.

aelf.StatePath

FieldTypeDescription
partsstringState path parts.

aelf.Transaction

FieldTypeDescription
fromAddressSender address.
toAddressContract address.
ref_block_numberint64Referenced block height.
ref_block_prefixbytesFirst 4 bytes of referenced block hash.
method_namestringMethod name in the contract.
paramsbytesMethod parameters.
signaturebytesSignature of the transaction.

aelf.TransactionExecutingStateSet

FieldTypeDescription
writesTransactionExecutingStateSet.WritesEntryChanged states.
readsTransactionExecutingStateSet.ReadsEntryRead states.
deletesTransactionExecutingStateSet.DeletesEntryDeleted states.

aelf.TransactionExecutingStateSet.DeletesEntry

FieldTypeDescription
keystring
valuebool

aelf.TransactionExecutingStateSet.ReadsEntry

FieldTypeDescription
keystring
valuebool

aelf.TransactionExecutingStateSet.WritesEntry

FieldTypeDescription
keystring
valuebytes

aelf.TransactionResult

FieldTypeDescription
transaction_idHashTransaction ID.
statusTransactionResultStatusTransaction result status.
logsLogEventLog events.
bloombytesBloom filter for transaction logs.
return_valuebytesReturn value of the transaction execution.
block_numberint64Block height that packages the transaction.
block_hashHashBlock hash that packages the transaction.
errorstringFailed execution error message.

aelf.TransactionResultStatus

NameNumberDescription
NOT_EXISTEDTransaction result does not exist.
PENDING1Transaction is waiting to be packaged.
FAILED2Transaction execution failed.
MINED3Transaction was successfully executed and packaged.
CONFLICT4Transaction has conflicts with other transactions.
PENDING_VALIDATION5Transaction is waiting for validation.
NODE_VALIDATION_FAILED6Transaction validation failed.

Usage#

aelf uses a key-value database to store data. State Path determines the key for contract execution data.

For example, a Token contract defines a balance property:

1
public MappedState<Address, string, long> Balances { get; set; }

To access the balance of an address (2EM5uV6bSJh6xJfZTUa1pZpYsYcCUAdPvZvFUJzMDJEx3rbioz) for a Token contract address (Nmjj7noTpMqZ522j76SDsFLhiKkThv1u3d4TxqJMD8v89tWmE), use its key in the database:

1
Nmjj7noTpMqZ522j76SDsFLhiKkThv1u3d4TxqJMD8v89tWmE/Balances/2EM5uV6bSJh6xJfZTUa1pZpYsYcCUAdPvZvFUJzMDJEx3rbioz/ELF

Parallel execution groups transactions by their State Paths. If two methods don’t access the same StatePath, they can be executed in parallel.

If State Paths mismatch, the transaction is canceled and labeled as “cannot be grouped”.

For more details, check the ITransactionGrouper and IParallelTransactionExecutingService code.

Implementation#

Example: Token Contract For the Transfer method, notify ITransactionGrouper via GetResourceInfo about the ELF balances of address A and B:

1
var args = TransferInput.Parser.ParseFrom(txn.Params);
2
var resourceInfo = new ResourceInfo
3
{
4
Paths =
5
{
6
GetPath(nameof(TokenContractState.Balances), txn.From.ToString(), args.Symbol),
7
GetPath(nameof(TokenContractState.Balances), args.To.ToString(), args.Symbol),
8
}
9
};
10
return resourceInfo;

The GetPath method forms a ScopedStatePath from key data:

1
private ScopedStatePath GetPath(params string[] parts)
2
{
3
return new ScopedStatePath
4
{
5
Address = Context.Self,
6
Path = new StatePath
7
{
8
Parts =
9
{
10
parts
11
}
12
}
13
}
14
}

Testing#

Construct two transactions and pass them to ITransactionGrouper to test if they can run in parallel using GroupAsync.

Prepare two stubs with different addresses:

1
var keyPair1 = SampleECKeyPairs.KeyPairs[0];
2
var acs2DemoContractStub1 = GetACS2DemoContractStub(keyPair1);
3
var keyPair2 = SampleECKeyPairs.KeyPairs[1];
4
var acs2DemoContractStub2 = GetACS2DemoContractStub(keyPair2);
1
var transactionGrouper = Application.ServiceProvider.GetRequiredService<ITransactionGrouper>();
2
var blockchainService = Application.ServiceProvider.GetRequiredService<IBlockchainService>();
3
var chain = await blockchainService.GetChainAsync();

Check with transactionGrouper:

1
// Situation can be parallel executed.
2
{
3
var groupedTransactions = await transactionGrouper.GroupAsync(new ChainContext
4
{
5
BlockHash = chain.BestChainHash,
6
BlockHeight = chain.BestChainHeight
7
}, new List<Transaction>
8
{
9
acs2DemoContractStub1.TransferCredits.GetTransaction(new TransferCreditsInput
10
{
11
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
12
Symbol = "ELF",
13
Amount = 1
14
}),
15
acs2DemoContractStub2.TransferCredits.GetTransaction(new TransferCreditsInput
16
{
17
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[3].PublicKey),
18
Symbol = "ELF",
19
Amount = 1
20
}),
21
});
22
groupedTransactions.Parallelizables.Count.ShouldBe(2);
23
}
24
// Situation cannot.
25
{
26
var groupedTransactions = await transactionGrouper.GroupAsync(new ChainContext
27
{
28
BlockHash = chain.BestChainHash,
29
BlockHeight = chain.BestChainHeight
30
}, new List<Transaction>
31
{
32
acs2DemoContractStub1.TransferCredits.GetTransaction(new TransferCreditsInput
33
{
34
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
35
Symbol = "ELF",
36
Amount = 1
37
}),
38
acs2DemoContractStub2.TransferCredits.GetTransaction(new TransferCreditsInput
39
{
40
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
41
Symbol = "ELF",
42
Amount = 1
43
}),
44
});
45
groupedTransactions.Parallelizables.Count.ShouldBe(1);
46
}

Example#

Refer to the MultiToken contract implementation for GetResourceInfo. Note that Transfer method needs to handle transaction fees along with keys.

ACS2 - Parallel Execution Standard

ACS2 enables parallel execution of transactions by providing necessary resource information.

Interface#

A contract inheriting ACS2 must implement:

Methods

Method NameRequest TypeResponse TypeDescription
GetResourceInfoaelf.Transactionacs2.ResourceInfoRetrieves resource dependencies for transaction exec.

Types#

acs2.ResourceInfo

FieldTypeDescriptionLabel
write_pathsaelf.ScopedStatePathState paths written during executionrepeated
read_pathsaelf.ScopedStatePathState paths read during executionrepeated
non_parallelizableboolIndicates if transaction is non-parallelizable.

Other Types (Omitted for brevity)

Several other types like aelf.Address, aelf.BinaryMerkleTree, aelf.LogEvent, etc., are used within acs2.ResourceInfo.

Usage#

aelf uses State Paths to manage data storage, ensuring transaction grouping based on accessed paths for efficient parallel execution.

Implementation#

Token contract, for example, modifies balances through method Transfer. GetResourceInfo must notify ITransactionGrouper of accessed state paths.

1
var args = TransferInput.Parser.ParseFrom(txn.Params);
2
var resourceInfo = new ResourceInfo
3
{
4
Paths =
5
{
6
GetPath(nameof(TokenContractState.Balances), txn.From.ToString(), args.Symbol),
7
GetPath(nameof(TokenContractState.Balances), args.To.ToString(), args.Symbol),
8
}
9
};
10
return resourceInfo;

Test#

Test transaction parallelizability using ITransactionGrouper's GroupAsync method with sample transactions.

1
var keyPair1 = SampleECKeyPairs.KeyPairs[0];
2
var acs2DemoContractStub1 = GetACS2DemoContractStub(keyPair1);
3
var keyPair2 = SampleECKeyPairs.KeyPairs[1];
4
var acs2DemoContractStub2 = GetACS2DemoContractStub(keyPair2);
5
6
var transactionGrouper = Application.ServiceProvider.GetRequiredService<ITransactionGrouper>();
7
var blockchainService = Application.ServiceProvider.GetRequiredService<IBlockchainService>();
8
var chain = await blockchainService.GetChainAsync();
9
10
// Test parallel execution scenario
11
{
12
var groupedTransactions = await transactionGrouper.GroupAsync(new ChainContext
13
{
14
BlockHash = chain.BestChainHash,
15
BlockHeight = chain.BestChainHeight
16
}, new List<Transaction>
17
{
18
acs2DemoContractStub1.TransferCredits.GetTransaction(new TransferCreditsInput
19
{
20
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
21
Symbol = "ELF",
22
Amount = 1
23
}),
24
acs2DemoContractStub2.TransferCredits.GetTransaction(new TransferCreditsInput
25
{
26
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[3].PublicKey),
27
Symbol = "ELF",
28
Amount = 1
29
}),
30
});
31
groupedTransactions.Parallelizables.Count.ShouldBe(2);
32
}
33
34
// Test non-parallel execution scenario
35
{
36
var groupedTransactions = await transactionGrouper.GroupAsync(new ChainContext
37
{
38
BlockHash = chain.BestChainHash,
39
BlockHeight = chain.BestChainHeight
40
}, new List<Transaction>
41
{
42
acs2DemoContractStub1.TransferCredits.GetTransaction(new TransferCreditsInput
43
{
44
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
45
Symbol = "ELF",
46
Amount = 1
47
}),
48
acs2DemoContractStub2.TransferCredits.GetTransaction(new TransferCreditsInput
49
{
50
To = Address.FromPublicKey(SampleECKeyPairs.KeyPairs[2].PublicKey),
51
Symbol = "ELF",
52
Amount = 1
53
}),
54
});
55
groupedTransactions.Parallelizables.Count.ShouldBe(1);
56
}

Example#

For an example of implementing GetResourceInfo, refer to the MultiToken contract, ensuring transaction fees are considered for the keys involved.

Edited on: 15 July 2024 04:40:14 GMT+0