hiero-ledger / hiero-sdk-cpp

C++ SDK for Hiero
Apache License 2.0
29 stars 15 forks source link

Check if generated transaction IDs are unique #499

Open thenswan opened 1 year ago

thenswan commented 1 year ago

Description

Ref issue in the Java SDK, which is going to be fixed with this PR - please check if we have the same issue in the C++ SDK.

Steps to reproduce

There is a sample code, which was used in the Java SDK for testing. testGenerateId uses TransactionId.generate() and fails after ~100K IDs. testGenerateId2 uses a monotonic clock and passes on 1M ids.

@Test
    void testGenerateId() {
        TransactionId[] ids = new TransactionId[1000000];
        AccountId accountId = AccountId.fromString("0.0.1000");
        for (int i = 0; i < ids.length; ++i) {
            ids[i] = TransactionId.generate(accountId);
        }
        HashSet<TransactionId> set = new HashSet<>(ids.length);
        for (int i = 0; i < ids.length; ++i) {
            assertThat(set.add(ids[i])).as("ids[%d] is not unique", i).isTrue();
        }
    }

    private final AtomicLong monotonicTime = new AtomicLong();

    TransactionId generate(AccountId accountId) {
        long currentTime;
        long lastTime;
        do {
            currentTime = System.currentTimeMillis() * 1_000_000L;
            lastTime = monotonicTime.get();
            if (currentTime <= lastTime) currentTime = lastTime + 1000L;
        } while (!monotonicTime.compareAndSet(lastTime, currentTime));
        return new TransactionId(accountId, Instant.ofEpochSecond(0, currentTime));
    }

    @Test
    void testGenerateId2() {
        TransactionId[] ids = new TransactionId[1000000];
        AccountId accountId = AccountId.fromString("0.0.1000");
        for (int i = 0; i < ids.length; ++i) {
            ids[i] = generate(accountId);
        }
        HashSet<TransactionId> set = new HashSet<>(ids.length);
        for (int i = 0; i < ids.length; ++i) {
            assertThat(set.add(ids[i])).as("ids[%d] is not unique", i).isTrue();
        }
    }

Additional context

No response

Hedera network

other

Version

v0.15.0

Operating system

None

SimiHunjan commented 8 months ago

Research issue