Commit Graph

1247 Commits

Author SHA1 Message Date
CalDescent
8260cec713 Added "maximumCount" parameter to HSQLDBATRepository.getMatchingFinalATStatesQuorum() and use it to limit the number of ATs being returned in the query.
Initially set to 10 when used by the /crosschain/price/{blockchain} API, so that the price is based on the last 10 trades rather than every trade that has ever taken place.
2021-05-09 15:56:15 +01:00
CalDescent
f4520e2752 Skip Block.logDebugInfo() altogether if the log level is more specific than DEBUG, to avoid wasting resources. 2021-05-09 09:00:53 +01:00
CalDescent
475802afbc Fixed divide by zero exception.
Block.calcKeyDistance() cannot be called on some trimmed blocks, because the minter level is unable to be inferred in some cases. This generally hasn't been an issue, but the new Block.logDebugInfo() method is invoking it for all blocks. For now I am adding defensiveness to the debug method, but longer term we might want to add defensiveness to Block.calcKeyDistance() itself, if we ever encounter this issue again. I will leave it alone for now, to reduce risk.
2021-05-09 08:25:24 +01:00
CalDescent
fe4ae61552 Added "maxRetries" setting.
This controls the maximum number of retry attempts if a peer fails to respond with the requested data.
2021-05-06 17:49:45 +01:00
CalDescent
6109bdeafe Set go-live timestamp for same-length chain weight consensus: 1620579600000 2021-05-05 18:40:07 +01:00
CalDescent
6e9a61c4e5 Fixed logging issue where it would underreport the number of common blocks found when loading some from the cache. 2021-05-02 20:51:53 +01:00
CalDescent
8e244fd956 Fixed yet another bug with minChainLength. 2021-05-02 20:45:20 +01:00
CalDescent
2eb6771963 Adapted logging in comparePeers() to report correct values for both chain weight algorithms. 2021-05-02 20:26:51 +01:00
CalDescent
db77108054 Log the number of blocks used in Block.calcChainWeight()
This makes it easier to check that the new consensus code is being used, and that it is working correctly.
2021-05-02 19:59:32 +01:00
CalDescent
241e2bef85 Merge branch 'master' into chain-weight-consensus
# Conflicts:
#	src/main/java/org/qortal/block/BlockChain.java
#	src/main/resources/blockchain.json
#	src/test/resources/test-chain-v2-founder-rewards.json
#	src/test/resources/test-chain-v2-leftover-reward.json
#	src/test/resources/test-chain-v2-minting.json
#	src/test/resources/test-chain-v2-qora-holder-extremes.json
#	src/test/resources/test-chain-v2-qora-holder.json
#	src/test/resources/test-chain-v2-reward-scaling.json
#	src/test/resources/test-chain-v2.json
2021-05-02 18:18:20 +01:00
CalDescent
fac02dbc7d Fixed bug in maxHeight parameter passed to Block.calcChainWeight()
Like the others, this one is only relevant after switching to same-length chain weight comparisons.
2021-05-02 15:56:13 +01:00
CalDescent
9ebcd55ff5 Fixed calculation error in existing chain weight code, which would have caused the last block to be missed out of the comparison after switching to same-length chain comparisons. 2021-05-01 13:34:13 +01:00
CalDescent
50244c1c40 Fixed bug which would cause other peers to not be compared against each other, if we had no blocks ourselves.
Again, this wouldn't have affected anything in 1.5.0 or before, but it will become more significant if we switch to same-length chain weight comparisons.
2021-05-01 13:32:16 +01:00
CalDescent
b4395fdad1 Fixed bug which could cause minChainLength to report a higher value.
This wouldn't have affected anything in 1.5.0, but it will become more significant if we switch to same-length chain weight comparisons.
2021-05-01 10:57:24 +01:00
CalDescent
1da8994be7 Log the block timestamp, minter level, online accounts, key distance, and weight, when orphaning or processing.
This gives an insight into the contents of each chain when doing a re-org. To enable this logging, add the following to log4j2.properties:

logger.block.name = org.qortal.block.Block
logger.block.level = debug
2021-05-01 10:24:50 +01:00
55ff1e2bb1
updated and tested BTC electrum servers (#36)
* updated electrum servers

mainnet list: https://1209k.com/bitcoin-eye/ele.php?chain=btc
testnet list: https://1209k.com/bitcoin-eye/ele.php?chain=tbtc

* removed servers

tested each mainnet server individually and removed those that did not respond
2021-05-01 09:18:46 +01:00
CalDescent
5fd8528c49 Small refactor for code readability, and added some defensiveness to avoid possible NPEs. 2021-04-29 09:04:59 +01:00
CalDescent
26d8ed783a Same as commit c0c5bf1, but for blocks as well as block summaries. 2021-04-29 08:55:16 +01:00
CalDescent
c0c5bf1591 Apply blocks in syncToPeerChain() if the latest received block is newer than our latest, and we started from an out of date chain.
This solves a common problem that is mostly seen when starting a node that has been switched off for some time, or when starting from a bootstrap. In these cases, it can be difficult get synced to the latest if you are starting from a small fork. This is because it required that the node was brought up to date via a single peer, and there wasn't much room for error if it failed to retrieve a block a couple of times. This generally caused the blocks to be thrown away and it would try the same process over and over.

The solution is to apply new blocks if the most recently received block is newer than our current latest block. This gets the node back on to the main fork where it can then sync using the regular applyNewBlocks() method.
2021-04-28 22:03:13 +01:00
CalDescent
a9a0e69ec0 Set go-live block height for share bin fix: block 399000 2021-04-26 17:19:39 +01:00
CalDescent
ea1fed2fd3 Merge branch 'block-reward-distribution-fix' 2021-04-26 17:16:14 +01:00
CalDescent
b37f2c7d7f MAXIMUM_RETRIES set to 2, as 3 retries may have been slightly too many. 2021-04-26 17:08:21 +01:00
CalDescent
0c0c5ff077 Invalidate our block summaries cache for a peer if it fails to respond with signatures when synchronizing. 2021-04-25 12:50:40 +01:00
CalDescent
e12b99d17e Invalidate our common block cache for a peer if we can't find a common block when synchronizing. 2021-04-25 09:37:32 +01:00
CalDescent
d599146c3a Cache peer block summaries to avoid duplicate requests when comparing peers. 2021-04-24 22:10:40 +01:00
CalDescent
476731a2c3 In syncToPeerChain(), only apply a partial set of peer's blocks if they are recent.
If a peer fails to reply with all requested blocks, we will now only apply the blocks we have received so far if at least one of them is recent. This should prevent or greatly reduce the scenario where our chain is taken from a recent to an outdated state due to only partially syncing with a peer. It is best to keep our chain "recent" if possible, as this ensures that the peer selection code always runs, and therefore avoids unnecessarily syncing to a random peer on an inferior chain.
2021-04-24 20:12:11 +01:00
CalDescent
1e491dd8fb MAXIMUM_RETRIES increased from 1 to 3.
Now that we are spending a lot of time to carefully select a peer to sync with, it makes sense to retry a couple more times before giving up and starting the peer selection process all over again.
2021-04-24 19:45:53 +01:00
CalDescent
ba6397b963 Improved logging, to give a clearer picture of the peer selection decisions. 2021-04-24 19:23:09 +01:00
CalDescent
3146da6aec Don't add to the inferior chain signatures list when comparing peers against each other.
In these comparisons it's easy to incorrectly identify a bad chain, as we aren't comparing the same number of blocks. It's quite common for one peer to fail to return all blocks and be marked as an inferior chain, yet we have other "good" peers on that exact same chain. In those cases we would have stopped talking to the good peers again until they received another block.

Instead of complicating the logic and keeping track of the various good chain tip signatures, it is simpler to just remove the inferior peers from this round of syncing, and re-test them in the next round, in case they are in fact superior or equal.
2021-04-24 16:43:29 +01:00
CalDescent
5643e57ede Fixed string formatting error. 2021-04-24 16:21:04 +01:00
CalDescent
f532dbe7b4 Optimized code in Synchronizer.uniqueCommonBlocks() 2021-04-24 15:22:29 +01:00
CalDescent
ec2af62b4d Fix for bug which failed to remove peers without block summaries.
The iterator was removing the peer from the "peersSharingCommonBlock" array, when it should have been removing it from the "peers" array. The result was that the bad peer would end up in the final list of good peers, and we could then sync with it when we shouldn't have.
2021-04-24 15:21:30 +01:00
CalDescent
423142d730 Tidied up RECOVERY_MODE_TIMEOUT constant, and made checkRecoveryModeForPeers() private. 2021-04-24 10:35:01 +01:00
CalDescent
bdddb526da Added recovery mode, which is designed to automatically bring back a stalled network.
The existing system was unable to resume without manual intervention if it stalled for more than 7.5 minutes. After this time, no peers would have "recent' blocks, which are prerequisites for synchronization and minting.

This new code monitors for such a situation, and enters "recovery mode" if there are no peers with recent blocks for at least 10 minutes. It also requires that there is at least one connected peer, to reduce false positives due to bad network connectivity.

Once in recovery mode, peers with no recent blocks are added back into the pool of available peers to sync with, and restrictions on minting are lifted. This should allow for peers to collaborate to bring the chain back to a "recent" block height. Once we have a peer with a recent block, the node will exit recovery mode and sync as normal.

Previously, lifting minting restrictions could have increased the risk of extra forks, however it is much less risky now that nodes no longer mint multiple blocks in a row.

In all cases, minBlockchainPeers is used, so a minimum number of connected peers is required for syncing and minting in recovery mode, too.
2021-04-23 09:21:15 +01:00
CalDescent
dbf1ed40b3 Log the parent block's signature when minting a new block, to help us keep track of the chain it's being minted on. 2021-04-19 09:33:24 +01:00
CalDescent
02ace06526 Revert "When syncing to a peer on a different fork, ensure that all blocks are obtained before applying them."
This reverts commit c919797553.
2021-04-18 13:03:04 +01:00
CalDescent
2d2bfc0a4c Log the number of common blocks found in each search. 2021-04-18 13:02:38 +01:00
CalDescent
3c22a12cbb Experimental idea to prevent a single node signing more than one block in a row.
This could drastically reduce the number of forks being created. Currently, if a node is having problems syncing, it will continue adding to its own fork, which adds confusion to the network. With this new idea, the node would be prevented from adding to its own chain and is instead forced to wait until it has retrieved the next block from the network.

We will need to test this on the testnet very carefully. My worry is that, because all minters submit blocks, it could create a situation where the first block is submitted by everyone, and the second block is submitted by no-one, until a different candidate for the first block has been obtained from a peer. This may not be a problem at all, and could actually improve stability in a huge way, but at the same time it has the potential to introduce serious network problems if we are not careful.
2021-04-18 10:26:36 +01:00
CalDescent
3071ef2f36 Removed redundant uiLocalServers 2021-04-17 20:55:30 +01:00
CalDescent
3022cb22d6 Merge branch 'master' into prioritize-peers 2021-04-17 20:51:35 +01:00
CalDescent
e9b4a3f6b3 Automatically backup trade bot data when starting a new trade (from either side). 2021-04-17 20:45:35 +01:00
CalDescent
4312ebfcc3 Adapted the HSQLDBRepository.exportNodeLocalData() method
It now has a new parameter - keepArchivedCopy - which when set to true will cause it to rename an existing TradeBotStates.script to TradeBotStates-archive-<timestamp>.script before creating a new backup. This should avoid keys being lost if a new backup is taken after replacing the db.

In a future version we can improve this in such a way that it combines existing and new backups into a single file. This is just a "quick fix" to increase the chances of keys being recoverable after accidentally bootstrapping without a backup.
2021-04-17 20:44:57 +01:00
CalDescent
2c0e099d1c Removed wildcard import that was automatically introduced by Intellij. 2021-04-17 14:36:24 +01:00
CalDescent
b1eb02eb1d
Merge pull request #33 from QuickMythril/version-on-tooltip
add version on tooltip
2021-04-17 13:21:20 +01:00
CalDescent
c919797553 When syncing to a peer on a different fork, ensure that all blocks are obtained before applying them.
In version 1.4.6, we would still sync with a peer even if we only received a partial number of the requested blocks/summaries. This could create a new problem, because the BlockMinter would often try and make up the difference by minting a new fork of up to 5 blocks in quick succession. This could have added to network confusion.

Longer term we may want to adjust the BlockMinter code to prevent this from taking place altogether, but in the short term I will revert this change from 1.4.6 until we have a better way.
2021-04-17 13:09:52 +01:00
CalDescent
08dacab05c Make sure to give up if we are requesting block summaries when the core needs to shut down. 2021-04-17 12:57:28 +01:00
CalDescent
2efc9218df Improved the process of selecting the next peer to sync with
Added a new step, which attempts to filter out peers that are on inferior chains, by comparing them against each other and our chain. The basic logic is as follows:

1. Take the list of peers that we'd previously have chosen from randomly.
2. Figure out our common block with each of those peers (if its within 240 blocks), using cached data if possible.
3. Remove peers with no common block.
4. Find the earliest common block, and compare all peers with that common block against each other (and against our chain) using the chain weight method. This involves fetching (up to 200) summaries from each peer after the common block, and (up to 200) summaries from our own chain after the common block.
5. If our chain was superior, remove all peers with this common block, then move up to the next common block (in ascending order), and repeat from step 4.
6. If our chain was inferior, remove any peers with lower weights, then remove all peers with higher common blocks.
7. We end up with a reduced list of peers, that should in theory be on superior or equal chains to us. Pick one of those at random and sync to it.

This is a high risk feature - we don't yet know the impact on network load. Nor do we know whether it will cause issues due to prioritising longer chains, since the chain weight algorithm currently prefers them.
2021-04-17 12:52:19 +01:00
CalDescent
41505dae11 Treat two block summaries as equal if they have matching signatures 2021-04-16 09:40:22 +01:00
CalDescent
8d613a6472 MAXIMUM_RETRIES reduced from 3 to 1 2021-03-30 13:07:34 +01:00
CalDescent
c3e5298ecd Added a few checks for Controller.isStopping() in synchronizer loops, to try and speed up the shutdown time. 2021-03-30 13:05:43 +01:00
CalDescent
e89d31eb5a Rewrite of Synchronizer.syncToPeerChain(), this time borrowing ideas from Synchronizer.applyNewBlocks().
Main differences / improvements:
- Only request a single batch of signatures upfront, instead of the entire peer's chain. There is no point in requesting them all, as the later ones may not be valid by the time we have finished requesting all the blocks before them.
- If we fail to fetch a block, clear any queued signatures that are in memory and re-fetch signatures after the last block received. This allows us to cope with peers that re-org whilst we are syncing with them.
- If we can't find any more block signatures, or the peer fails to respond to a block, apply our progress anyway. This should reduce wasted work and network congestion, and helps cope with larger peer re-orgs.
- The retry mechanism remains in place, but instead of fetching the same incorrect block over and over, it will attempt to locate a new block signature each time, as described above. To help reduce code complexity, block signature requests are no longer retried.
2021-03-30 12:29:27 +01:00
catbref
d9d4c4c302 Bump Peer response timeout from 2s to 3s 2021-03-21 16:17:40 +00:00
catbref
81c6d75d62 Adjust Synchronizer.MAXIMUM_BLOCK_STEP to 128, which means final summaries request will have enough to cover MAXIMUM_COMMON_DELTA (8+16+32+64+128 = 248, which is >240) 2021-03-21 16:12:41 +00:00
catbref
d1419bdfbd Minor comments, adjust max step size when searching for common block 2021-03-21 15:57:00 +00:00
CalDescent
8566d9b7e5 Merge branch 'master' into synchronization-improvements 2021-03-21 15:04:43 +00:00
catbref
b319d6db6b Rework BlockMessage caching with new pseudo outgoing-only message that only caches raw bytes 2021-03-21 14:14:15 +00:00
CalDescent
35fd1d8455 Base58 encode signatures in recently added logs. 2021-03-21 14:12:04 +00:00
CalDescent
be21771e49 Use SYNC_BATCH_SIZE instead of MAXIMUM_BLOCK_SIGNATURES_PER_REQUEST. 2021-03-21 13:58:42 +00:00
catbref
745528a9b1 Peer.sendMessage() should return false when it can't send because it can't build the message 2021-03-21 13:19:59 +00:00
CalDescent
f1422af95b Added retry mechanisms in Synchronizer.syncToPeerChain()
Until now, we required a perfect success rate when syncing with a peer via Synchronizer.syncToPeerChain(). Blocks were requested individually, but the node would give up and lose all progress if a single request failed. In practice, this happened very regularly, and it was difficult to succeed when there were a large number of blocks (e.g. 20+) that needed to be requested.

This commit adds two retry mechanisms, causing each of the two request types (block sigs and blocks) to retry 3 times before giving up, potentially avoiding a lot of wasted work. The number of retries is configurable in the MAXIMUM_RETRIES constant, which we could move to settings at some point if this feature proves useful.

The original issue seemed to result in a few side effects:

1. Nodes would spend a large amount of time requesting blocks from peers, only to throw it all away afterwards. This potentially added to network congestion, as nodes were using unnecessary network time to unproductively serve peers.

2. A large number of sync attempts were failing, particularly when a fork emerged with a significant number of divergent blocks (20+). This issue reduced the ability for nodes to sync to the correct chain while they still had time to do so. With every block that passed, it became made it more and more difficult to switch to the correct chain. Eventually, the correct chain would become TOO_DIVERGENT at which point there is no way to automatically switch without manual intervention. I hope that this retry mechanism will increase the chances of nodes automatically moving onto the right chain quickly, avoiding the need for a user to intervene.

3. The POST /admin/forcesync API was unlikely to succeed when the peer's chain had started to diverge from the user's chain. This should increase the success rate.

Also included in this commit is a MAXIMUM_BLOCK_SIGNATURES_PER_REQUEST constant. This limits the number of block sigs requested in each batch (default 200). Without this, we are unable to increase MAXIMUM_COMMON_DELTA because it can try and request thousands of block sigs at once, which unsurprisingly doesn't succeed.
2021-03-21 09:41:36 +00:00
CalDescent
f92f4dc1e2 Fixed some log entries in Controller.syncToPeerChain() which were incorrectly reporting our height instead of the height of block(s) being requested from the peer. Now reporting the height of the block (or block sigs) being retrieved, which should make it easier to interpret the logs. 2021-03-20 16:18:25 +00:00
catbref
019cfdc1db Minor comment re-org 2021-03-20 11:45:11 +00:00
CalDescent
e694a51cdd Fix for "numberSignaturesRequired" calculation error in Synchronizer.syncToPeerChain()
This bug often prevented the correct amount of block signatures (and blocks) from being requested from a peer, when trying to sync to it.

It could result in quite serious consequences, as it would trigger orphaning back to the common block without first requesting all of the necessary blocks from the peer's chain. Rather than applying a complete copy of the peer's chain, it could orphan back to the common block and then only apply a few blocks beyond that, leaving the node in an unexpected state, potentially hundreds of blocks behind the peer's current height, which it then has to try and obtain from other peers.

When there are forks present, this could result in it hopping from chain to chain, each time being unable to fully synchronise with the peer. Given that we currently discard our chain if it is deemed that our latest block isn't "recent", it is very important that nodes are brought up to the latest block when synchronising with a peer, to avoid constantly triggering discards.

The severity of this bug increased when there was a large disparity between the peer's latest block and the common block height, and prevented us from being able to increase MAXIMUM_COMMON_DELTA.
2021-03-20 10:33:23 +00:00
CalDescent
16453ed602 Added unit tests for level 3+4, 5+6, 7+8, and 9+10 rewards.
These are simpler than the level 1+2 tests; they only test that the rewards are correct for each level post-shareBinFix. I don't think we need multiple instances of the pre-shareBinFix or block orphaning tests. There are a few subtle differences between each test, such as the online status of Bob, in order the make the tests slightly more comprehensive.
2021-03-17 08:50:53 +00:00
CalDescent
fde68dc598 Added unit test to test level 1 and 2 rewards.
1. Assign 3 minters (one founder, one level 1, one level 2)
2. Mint a block after the shareBinFix, ensuring that level 1 and 2 are being rewarded evenly from the same share bin.
3. Orphan the block and ensure the rewards are reversed.
4. Orphan two more blocks, each time checking that the balances are being reduced in accordance with the pre-shareBinFix mapping.
2021-03-16 09:11:49 +00:00
22e3140ff0
add version on tooltip
add Version Number on Qortal Core tooltip.

https://i.imgur.com/eLnLnQ5.png
2021-03-16 03:00:55 -04:00
catbref
ec7d4f4498 Changed "too busy" logging from debug to trace 2021-03-13 18:30:43 +00:00
catbref
d635de44a8 Added TODO in HSQLDBRepository about deadlock log spam 2021-03-13 18:29:31 +00:00
catbref
bce66bf57f Move HSQLDBRepositoryFactory.POOL_SIZE into Settings as "repositoryConnectionPoolSize" 2021-03-13 18:14:11 +00:00
catbref
0fc5153f9b Merge 'trade-bot-timeout-fix' into master 2021-03-13 17:13:40 +00:00
catbref
0398c2fae1 Try to avoid clogging up network threads by discarding incoming TRANSACTION messages if we're too busy
As importing a transaction requires blockchain lock, all the network threads
can be used up blocking for that lock, especially if Synchronizer is active.

So we simply discard incoming TRANSACTION messages if we can't immediately
obtain the blockchain lock. Some other peer will probably attempt to
send the transaction soon again anyway.

Plus we swap transaction lists after connection handshake.
2021-03-13 17:03:38 +00:00
CalDescent
5fc495eb6a Fix for possible logic bug introduced in commit 33a8f31. 2021-03-12 22:05:38 +00:00
CalDescent
847e81e95c Fixed a mapping issue in Block->getShareBins(), to take effect at some future (undecided) height.
Post trigger, account levels will map correctly to share bins, subtracting 1 to account for the 0th element of the shareBinsByLevel array.
Pre-trigger, the legacy mapping will remain in effect.
2021-03-12 19:48:49 +00:00
CalDescent
7918622e2e
Merge pull request #31 from sakumatto/master
Initial Italian translation by Pabs 2021
2021-03-11 11:06:03 +00:00
CalDescent
427fa1816d "blockCacheSize" can now be configured via settings.json. 2021-03-07 10:00:49 +00:00
catbref
be3af53011 Set new block sig go-live block height: block 320000 2021-02-27 18:23:49 +00:00
catbref
414399b2a0 Merge branch 'blocksig' into master 2021-02-27 18:20:13 +00:00
catbref
c592051a80 Speed up BlockMinter by filtering out 'unconfirmable' transaction types like CHAT & PRESENCE 2021-02-27 17:29:19 +00:00
catbref
33a8f311e5 Reduce logging noise from lost trade-bot ATs and self-clean if AT does not exist after 24 hours 2021-02-24 21:00:52 +00:00
catbref
018c3cdcd4 Allow users to delete trade-bot entries in any state if corresponding AT does not exist 2021-02-24 20:46:47 +00:00
sakumatto
384dffbf9a Initial Italian translation by Pabs 2021
UI localized to Italian by @Pabs
2021-02-22 20:03:11 +02:00
catbref
3920933fc7 Add block fetch TRACE logging to Synchronizer 2021-02-20 13:36:54 +00:00
catbref
1fdd7f156c Reduced logging noise from deleteExpiredTransactions but increased detection & logging on "serilization failures" from HSQLDB 2021-02-20 13:25:53 +00:00
catbref
91925cf931 Change block "minter" signature code, to take effect at some future (undecided) height.
Post trigger, this change will use all 128 bytes of previous block's signature when
calculating/validating next block's "minter" signature (itself the first 64 bytes of a block signature).

Prior to trigger, current behaviour is to only use first 64 bytes of previous block's
signature, which doesn't encompass transactions signature.

New block sig code should help reduce forking and help improve transactional
security.

Added "newBlockSigHeight" to blockchain.json but initially set to block 999999
pending decision on when to merge, auto-update, go-live, etc.
2021-02-20 12:08:51 +00:00
catbref
3453f0efaf Rework HSQLDB CHECKPOINTing to defer until there are no ongoing SQL transactions, in order to prevent DB deadlocks.
Symptoms of a CHECKPOINT-related DB deadlock:

On Controller thread:
"Controller" #20 prio=5 os_prio=31 cpu=1577665.56ms elapsed=17666.97s allocated=475G defined_classes=412 tid=0x00007fe99f97b000 nid=0x1644b waiting on condition  [0x0000700009a21000]
   java.lang.Thread.State: WAITING (parking)
	at jdk.internal.misc.Unsafe.park(java.base@14.0.2/Native Method)
	- parking to wait for  <0x0000000602f2a6f8> (a org.hsqldb.lib.CountUpDownLatch$Sync)
[...some more lines...]
[this next line is the best indicator: ]
	at org.qortal.repository.hsqldb.HSQLDBRepository.checkpoint(HSQLDBRepository.java:385)
	at org.qortal.repository.RepositoryManager.checkpoint(RepositoryManager.java:51)
	at org.qortal.controller.Controller.run(Controller.java:544)

Other threads stuck at:
	- parking to wait for  <0x00000007ff09f0b0> (a org.hsqldb.lib.CountUpDownLatch$Sync)
	at java.util.concurrent.locks.LockSupport.park(java.base@14.0.2/LockSupport.java:211)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@14.0.2/AbstractQueuedSynchronizer.java:714)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(java.base@14.0.2/AbstractQueuedSynchronizer.java:1046)
	at org.hsqldb.lib.CountUpDownLatch.await(Unknown Source)
	at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
2021-02-13 17:32:09 +00:00
catbref
eb23940996 Fix potential NPE when trying to obtain opportunistic database connection.
Could have affected:
Controller.deleteExpiredTransactions()
Network.getConnectablePeer()
Network.opportunisticMergePeers()
Network.prunePeers()

Symptoms:

2021-02-12 16:46:06 WARN  NetworkProcessor:152 - [1556] exception while trying to produce task
java.lang.NullPointerException: null
        at org.qortal.repository.hsqldb.HSQLDBRepository.<init>(HSQLDBRepository.java:92) ~[qortal.jar:1.4.1]
        at org.qortal.repository.hsqldb.HSQLDBRepositoryFactory.tryRepository(HSQLDBRepositoryFactory.java:97) ~[qortal.jar:1.4.1]
        at org.qortal.repository.RepositoryManager.tryRepository(RepositoryManager.java:33) ~[qortal.jar:1.4.1]
        at org.qortal.network.Network.getConnectablePeer(Network.java:525) ~[qortal.jar:1.4.1]
2021-02-13 11:24:26 +00:00
catbref
6cd86d86a6 Add "atFindNextTransactionFix" feature-trigger to all test blockchain configs 2021-02-13 11:24:26 +00:00
sakumatto
b55154cd3c Initial translations of UI terms into Finnish
Initial translations of UI terms into Finnish language fi_ by Saku Mättö
2021-02-12 17:02:31 +02:00
catbref
1e6e5e66da Fix trailing comma on blockchain.json! 2021-02-06 12:09:24 +00:00
catbref
9b0e88ca87 Only compare same number of blocks when comparing peer chains 2021-02-06 11:40:29 +00:00
catbref
3acc0babb7 More chain-weight tests 2021-02-06 11:19:39 +00:00
catbref
20e4a79130 Reduce logging level for deleting older PRESENCE transactions 2021-01-17 16:49:47 +00:00
catbref
d336200d75 Fix for off-by-one bug when ATs look for next transaction. Currently configured to take effect block 275,000 2021-01-17 16:01:36 +00:00
catbref
e5bb3e2f0a Added defensive try-catch around network engine calls (actually ExecuteProduceConsume) 2021-01-17 15:34:50 +00:00
catbref
5b2b2bab46 Two-pronged fix for HSQLDB 'serialization failure' errors when receiving multiple PRESENCE transactions -- reported by marracc 2021-01-17 15:33:59 +00:00
catbref
c17eea3ed9 Added timeout to Peer sendMessage() - same timeout as for awaiting incoming responses 2021-01-17 15:32:39 +00:00
catbref
83f4e2f5bf Added API call to view single trade's detailed info 2021-01-17 15:31:44 +00:00
catbref
c8e7a00c08 Remove unused JDBC statement 2021-01-16 13:20:58 +00:00
catbref
190014cf96 Fix minor NPE during shutdown 2021-01-16 13:20:20 +00:00
catbref
385064e324 Return foreign-chain wallet transactions in newest-timestamp-first order 2021-01-08 17:37:12 +00:00
catbref
6eb9447bb9 Merge branch 'LTCv3-with-presence' into master 2021-01-07 07:45:47 +00:00
catbref
0ee8d7da0f Improve removal of expired PRESENCE txns in websocket cache 2020-12-31 11:26:13 +00:00
catbref
918a331609 Transaction.importAsUnconfirmed() now BLOCKS for blockchain lock, instead of non-blocking try()
This is a serious change as it affects many callers.

Controller.onNetworkTransactionMessager()
-- should be OK to block as it's only one EPC thread

TransactionsResource.processTransaction()
-- should be OK to block as it's only one Jetty thread
AND has its own 30s timeout wrapper anyway

Implementations of AcctTradeBot.progress()
e.g. BitcoinACCTv1TradeBot.progress() & LitecoinACCTv1TradeBot.progress()
TradeBot.updatePresence()
-- these are called via BlockMinter/Synchronizer
when blockchain lock is already held, so will are unaffected

AcctTradeBot.createTrade() and AcctTradeBot.startResponse()
-- these are called via API
and previously would only perform non-blocking blockchainLock.try()
but now perform blocking blockchainLock.lock()
thus preventing NO_BLOCKCHAIN_LOCK when creating/responding to trades
especially after a (wasted) MESSAGE PoW compute
but with potential downside that API response might be delayed
e.g. by a very slow sync round

Future work could look into removing the need for blockchain lock
when calling Transaction.importAsUnconfirmed().
2020-12-30 12:43:41 +00:00
catbref
41453f5bd1 Add primary key index to latest AT state cache for extra speed! 2020-12-29 17:57:20 +00:00
catbref
78f62751e5 TESTNET ONLY: Correct "LitcoinACCTv1" TradeBotStates.acct_name values in DB 2020-12-29 14:16:47 +00:00
catbref
d59c30757c Fix conversion of double in ElectrumX JSON to long 2020-12-29 12:17:55 +00:00
catbref
30d2e4fdac Correct logging message to blockchain-agnostic text 2020-12-29 12:16:40 +00:00
catbref
d43a074cc1 Use *ACCT*.class.getSimpleName() for less error-prone ACCT.NAME 2020-12-29 11:00:43 +00:00
catbref
27783dc6de Add WARNING on start-up if repository is missing latest AT state data 2020-12-29 10:34:25 +00:00
catbref
2a789a9a9b Add WARNING on start-up if repository is missing latest AT state data 2020-12-29 10:15:56 +00:00
catbref
a66dba767e Fix incorrect LatestATStates SQL table definition
This table was previously defined using the TEMPORARY keyword as the rows were used as a cached/index to speed up AT trimming SQL statements.

However, the table definition was lacking the "ON COMMIT PRESERVE ROWS" clause, and possibly the "GLOBAL" keyword, which caused the table contents to be emptied, immediately after being filled, when <tt>repository.saveChanges()</tt> was called (i.e. "COMMIT").

This caused latest AT states to be trimmed in error.

AtRepositoryTests.testGetLatestATStatePostTrimming also fixed so that it fails with the previous, broken code.
2020-12-29 09:19:03 +00:00
catbref
e00579e1a2 Fix incorrect LatestATStates SQL table definition
This table was previously defined using the TEMPORARY keyword as the rows were used as a cached/index to speed up AT trimming SQL statements.

However, the table definition was lacking the "ON COMMIT PRESERVE ROWS" clause, and possibly the "GLOBAL" keyword, which caused the table contents to be emptied, immediately after being filled, when <tt>repository.saveChanges()</tt> was called (i.e. "COMMIT").

This caused latest AT states to be trimmed in error.

AtRepositoryTests.testGetLatestATStatePostTrimming also fixed so that it fails with the previous, broken code.
2020-12-29 09:11:11 +00:00
catbref
99f1a55de2 Improve logging for case where trade offer is locked to someone else 2020-12-29 08:56:26 +00:00
catbref
3ec307a2a1 Don't allow more than one (active) trade-bot entry per trade-offer 2020-12-28 15:55:14 +00:00
catbref
3fdef9ea6d Fix P2SH refund "non-final" error issue
According to Bitcoin source, CheckFinalTx() in validation.cpp ~line 223,
we need to make sure median blocktime has passed P2SH refund transaction's
nLockTime.

Previously we were erroneously checking that median blocktime was in the past.

This should fix issues where refunding P2SH results in a "non-final" error
from the ElectrumX server network.
2020-12-28 15:44:45 +00:00
catbref
332c917c94 Fix ALICE-based PRESENCE transactions.
PRESENCE transactions were previously validated using Bob's trade key (in address form).
But as PRESENCE transactions are already emitted by Alice, her trade key is also used
(if present in trade data by virtue of AT being locked to Alice).

Similarly, Alice's trade-bot won't even try to build PRESENCE transactions if her
trade key isn't publicly visible to other peers, i.e. after AT is locked to Alice.
2020-12-28 12:00:11 +00:00
catbref
35b0ac78b8 Bump ElectrumX transaction cache size from 100 to 200 2020-12-24 16:52:58 +00:00
catbref
047627a6e5 Force bitcoinj keychain lookaheadThreshold to zero so we always generate more keys 2020-12-24 16:48:47 +00:00
catbref
5d6811bd50 Workaround for block 212937 issue 2020-12-23 15:02:14 +00:00
catbref
688f215dfd Allow PresenceType filtering on presence websocket via presenceType query param 2020-12-21 12:25:58 +00:00
catbref
7cbdbbcc8d Allow exception-free conversion from String to PresenceType 2020-12-21 12:25:11 +00:00
catbref
4e89b8fbac No need to create a map entry for null foreignBlockchain in TradeOffersWebSocket 2020-12-21 12:24:44 +00:00
catbref
70ec8cb11f Add public key in Qortal address form to tradeoffers and presence websockets
This aids matching PRESENCE to corresponding trade offers for use in UI.

Also tighten up visibility of some fields in ChainChainOfferSummary and
PresenceInfo to private.

PresenceInfo.address should map to CrossChainOfferSummary.qortalCreatorTradeAddress
which is "AT creator's ephemeral trading key-pair represented as Qortal address"
2020-12-18 11:42:53 +00:00
catbref
0f0266609f Add trading price estimate API call GET /crosschain/price/{blockchain} where blockchain is something like LITECOIN 2020-12-18 11:42:32 +00:00
catbref
ecfa6e994e Add API call POST /admin/repository/backup to trigger immediate backup 2020-12-16 12:52:19 +00:00
catbref
ed4a45f214 Force blocking DB backup to improve integrity of backup files 2020-12-16 12:51:30 +00:00
catbref
bd51806a0d Improve Block.getBytesForMinterSignature() 2020-12-14 15:05:31 +00:00
catbref
625dbfbbd7 Unify BlockInfo into BlockSummaryData, removing minterAddress (unused) and extra repository calls 2020-12-14 13:13:44 +00:00
catbref
1c6ea0a860 Improvements to ElectrumX, Bitcoin-y aspects, etc.
Add caching of transactions fetched via ElectrumX to reduce network load and speed up API response.

Fix handling ElectrumX servers that don't want to supply verbose transaction JSON.

Hide lots of data in BitcoinyTransaction that isn't needed by current API users.
2020-12-11 17:30:15 +00:00
catbref
3706cd5ff7 Return list, not set, of wallet transactions via API and provide better (usable) examples 2020-12-11 17:29:00 +00:00
catbref
934cd1d511 Add support for preferred blockchain to /websockets/crosschain/tradebot via foreignBlockchain query param 2020-12-10 17:08:32 +00:00
catbref
68e3d3b989 Add preferred-blockchain filtering to /websockets/crosschain/tradeoffers via foreignBlockchain query param 2020-12-10 16:00:01 +00:00
catbref
31fa916156 Add filtering by foreign blockchain to API crosschain calls 2020-12-10 14:52:06 +00:00
catbref
456bb3ca63 Include output addresses, if present, in BitcoinyTransaction 2020-12-10 14:01:40 +00:00
catbref
b07ad094c1 Fix DELETE /crosschain/tradebot by adding missing repository.saveChanges() 2020-12-10 13:11:48 +00:00
catbref
d766cfaa67 Fix API/websockets that were still BitcoinACCTv1-only 2020-12-10 12:48:46 +00:00
catbref
acc616c204 Add defensive code to EventBus to catch unexpected exceptions 2020-12-10 11:55:06 +00:00
catbref
8707f154ee Add support to ElectrumX for barring servers that don't give us the data we need 2020-12-10 11:32:09 +00:00
catbref
992427f0e0 Fix NPE due to unboxing null/no entry from PREVIOUS_STATES.get() in TradeBotWebSocket. Usually triggered when creating new trade-bot entry while having open websocket connection. 2020-12-10 11:31:37 +00:00
catbref
2c84add935 Bitcoiny improvements 2020-12-09 13:12:15 +00:00
catbref
e8fc91fd34 Minor work on ByteArray and associated tests 2020-12-08 15:19:12 +00:00
catbref
8c9cf4a02d Add API support for listing Bitcoin/Litecoin wallet transactions 2020-12-07 16:40:12 +00:00
catbref
23f0969b2d Requesting BTC/LTC wallet balance now accepts public key xpub/tpub too 2020-12-07 15:40:05 +00:00
catbref
cf82813280 Report foreignBlockchain and acctName in results for API call GET /crosschain/tradeoffers 2020-12-02 14:37:50 +00:00
catbref
753fa4dfa9 Remove extraneous boxing/unboxing from PresenceWebSocket 2020-12-02 13:20:37 +00:00
catbref
58ff338ab3 Now Transaction.importAsConfirmed() calls Controller.onNewTransaction(), removing call from API POST /transactions/process and Controller.onNetworkTransactionMessage() 2020-12-02 13:19:53 +00:00
catbref
064e12a57b Improve documentation regarding deadlock in EventBus 2020-12-02 13:16:18 +00:00
catbref
54bb8ed817 New PRESENCE-related API websocket at /websockets/presence 2020-12-01 17:24:02 +00:00
catbref
b651eae258 Notify EventBus with NewTransactionEvent in Controller.onNewTransaction 2020-12-01 17:23:10 +00:00
catbref
7562d9bbf8 Fix potential NPE when closing a websocket that failed to open properly 2020-12-01 17:22:40 +00:00
catbref
1b50dd5adf Modify API TransactionsResource to notify Controller after closing repository handle/session 2020-12-01 17:22:03 +00:00
catbref
c10a5db280 Fix PresenceTransaction to work with any ACCT, not only BitcoinACCTv1 2020-12-01 15:06:07 +00:00
catbref
500690be49 Add ATRepository.getAllATsByFunctionality() to fetch ATs matching selection of code hashes 2020-12-01 15:05:40 +00:00
catbref
778ac35ee6 Improve HSQLDBRepository.temporaryValuesTableSql to work with Collection, not just List 2020-12-01 15:04:50 +00:00
catbref
c16a664a78 Add toString() to ByteArray 2020-12-01 15:03:23 +00:00
catbref
75a265f89a Improve SupportedBlockchain enum 2020-12-01 15:02:58 +00:00
catbref
ddb55210b4 Merge branch 'presence-txn' into LTCv3-with-presence 2020-11-30 15:10:03 +00:00
catbref
e093520696 WIP: PRESENCE - TradeBot support, moved PresenceType enum, added Presence-only transaction deadline override 2020-11-27 18:06:24 +00:00
catbref
cfacddcb36 Change Controller.deleteExpiredTransactions to use Transaction-subclass .getDeadline() instance method call instead of static Transaction.getDeadline(transactionData) which allows Transaction subclasses to override with custom deadlines/expiry periods 2020-11-27 18:05:03 +00:00
catbref
d2dea3ff35 BlockMinter now notifies Controller of new block while still holding blockchain lock, bringing it in line with Synchronizer 2020-11-27 18:02:05 +00:00
catbref
a52c089728 WIP: PRESENCE transactions - support only TRADE_BOT type and restrict to known trades 2020-11-26 16:33:21 +00:00
catbref
15d25649b2 WIP: PRESENCE transactions - repository support, removing older versions, tests 2020-11-26 16:11:11 +00:00
catbref
e0210635e3 Add repository support for fetching subset of unconfirmed transactions by type and/or creator 2020-11-26 16:10:13 +00:00
catbref
90b993e234 Refactor post-importAsUnconfirmed as method to be overridden by Transaction subclasses, e.g. CHAT 2020-11-26 16:08:56 +00:00
catbref
9b7c2c50fb Initial commit with PRESENCE transaction type -- untested 2020-11-24 17:02:05 +00:00
catbref
a12045c19e Fix repository race condition from using wrong synchronization object
Previous fixes for "transaction rollback: serialization failure" when updating trim heights
in commits 16397852 and 58ed7205 had the right idea but were broken due to being synchronized
on different objects.

this.repository.trimHeightsLock would be a new Object() for each repository connection/session
and so not actually synchronize concurrent updates.

Implicit saveChanges()/COMMIT is still needed.

Fix is to use a repository-wide object for synchronization - in this case the repositoryFactory
object as held by RepositoryManager.

Added test to cover.

Also reduced DB trim height read to one call at start of thread for both trimming threads.
2020-11-17 14:53:39 +00:00
catbref
fccb3a3f0c Merge branch 'master' into LTCv3-merge-test 2020-11-13 10:46:45 +00:00
catbref
62ae49b639 ApiError_de.properties & SysTray_zh.properties also converted to UTF8 2020-11-12 12:18:26 +00:00
catbref
2e8f58bb2f ApiError_ru.properties & TransactionValidity_ru.properties converted to UTF8 for easier management 2020-11-12 11:34:25 +00:00
catbref
9e98ce220f Revert SysTray_ru.properties back to UTF8 form 2020-11-12 11:28:01 +00:00
catbref
a310e751bb Fix slow SQL query in HSQLDBATRepository.getBlockATStatesAtHeight() - mostly used during orphaning 2020-11-10 16:58:24 +00:00
catbref
a9c7142d7b Speed up AT states reshape 2020-11-10 16:46:07 +00:00
catbref
7a40c3526f Bugfixes and tests for SLEEP_UNTIL_MESSAGE 2020-11-10 15:44:47 +00:00
catbref
3253d9d3fb WIP: initial implementation of AT sleep-until-message (untested) 2020-11-10 15:44:47 +00:00
catbref
3ef8b81e51 Fix incorrect column indexes when fetching frozen AT data 2020-11-10 15:38:15 +00:00
catbref
1f409235e4 Don't rebuild repository or export node-local data during repository build if repository was 'pristine'.
Under certain conditions, e.g. non-existent database files, the repository would be created
and then immediately be re-created.

Not only was this unnecessary, but HSQLDBDatabaseUpdates would attempt to export the node-local
data twice, which would cause an error due to existing .script files.

The fix is three-pronged:

1. Don't immediately rebuild the repository if it's only just been built
2. Don't export the empty node-local data if repository has only just been built
3. Don't export the node-local data if it's empty
2020-11-09 10:31:21 +00:00
catbref
806baa6ae4 Fix API call referenced in DB reshape 2020-11-06 11:23:35 +00:00
catbref
58ed72058f Another attempt to prevent "serialization failure" during trimming 2020-11-05 14:36:14 +00:00
catbref
253a994438 Add API POST /repository/checkpoint call. Renamed GET/POST /admin/repository calls to /admin/repository/data 2020-11-05 11:08:54 +00:00
catbref
5549eded38 Improve/fix use of latest block cache, for more cache hits, faster chain-tip response, etc. 2020-11-05 09:34:57 +00:00
catbref
20777363cf Split AT state storage into two HSQLDB table for better management
This involves a database reshape, but before this happens the node-local
data is exported to local files, giving the user the option to use a
bootstrap file instead of waiting.
2020-11-04 20:07:30 +00:00
catbref
b3f859f290 Don't use WITH COLUMN NAMES when exporting data from repository into local file 2020-11-04 15:48:52 +00:00
catbref
8c9f68a9c3 Add API calls for exporting node-local repository data & corresponding import to/from local files 2020-11-04 15:35:42 +00:00
catbref
41f178bf59 Add support for API key security, where X-API-KEY header must match apiKey from settings
apiKey in settings is null by default at this point, for backwards compatibility.
In the future, the Windows installer could generate a UUID for apiKey.
apiKey in settings needs to be at least 8 characters.

API calls in the documentation engine are now marked with an open/closed padlock
to show where API key might be required.
Add support for API key security, where X-API-KEY header must match apiKey from settings

apiKey in settings is null by default at this point, for backwards compatibility.
In the future, the Windows installer could generate a UUID for apiKey.
apiKey in settings needs to be at least 8 characters.

API calls in the documentation engine are now marked with an open/closed padlock
to show where API key might be required.
2020-11-04 15:35:20 +00:00
catbref
ad5050f92e Add support for exporting node-local repository data to .script files and corresponding import function 2020-11-04 15:29:10 +00:00
catbref
16397852ae Add synchronization around updating trim heights to prevent deadlock/rollback 2020-11-04 10:01:20 +00:00
catbref
c125a53655 More (optionally) logging when comparing chains with peers. Support for potential future minor consensus change. 2020-11-02 11:52:06 +00:00
catbref
7b056a832f Turn off HSQLDB redo-log "blockchain.log" and periodically call "CHECKPOINT" instead.
Checkpointing interval is 1 hour by default, changable in settings via
"repositoryCheckpointInterval"
plus corresponding "showCheckpointNotifications" SysTray flags (off by default).

Added entries to SysTray_en i18n properties, and converted SysTray_ru to ISO-8559-1.
2020-11-02 11:49:21 +00:00
catbref
6c40727027 More reporting for slow HSQLDB queries/commits 2020-11-02 11:16:40 +00:00
catbref
8f06765caf Networking performance improvements and message sending bugfix 2020-11-02 11:15:53 +00:00
catbref
de2fc78ad1 Add support for SHA256 digest of ByteBuffer in Crypto class 2020-11-02 10:47:27 +00:00
catbref
ee08410260 More trace-level debugging in Synchronizer to help diagnose chain reorg issues 2020-11-02 10:46:51 +00:00
catbref
88da8d949f Don't allow latest blocks cache to be empty 2020-11-02 10:45:21 +00:00
catbref
d2a92db921 More caching for GetBlockMessage. Added API call GET /admin/enginestats to monitor cache usage 2020-10-29 11:02:02 +00:00
catbref
f3b8258067 Add more latest block caching to reduce repository accesses, especially for requests from remote peers 2020-10-28 08:46:30 +00:00
catbref
da78c73485 Remove extraneous call to Controller.onNewBlock() after synchronization, as this call is performed per-block inside Synchronizer 2020-10-28 08:42:59 +00:00
catbref
cec25ce279 Add API call POST /peers/commonblock <connected-peer> as debugging aid 2020-10-28 08:41:23 +00:00
catbref
0389007491 Skip trimming while performing synchronization 2020-10-28 08:38:11 +00:00
catbref
38a64bdd9e Prevent HSQLDB prepared statement cache invalidation when rebuilding latest AT states cache 2020-10-12 14:35:10 +01:00
catbref
98564aa8bf Fix SQL logic error when fetching trade offers 2020-10-07 14:56:05 +01:00
catbref
6a4388fecc Use cached PreparedStatement for HSQLDB.assertEmptyTransaction + other minor HSQLDB fixes 2020-10-07 09:45:44 +01:00
catbref
1958444bc4 Add recipient indexes for payment/AT transactions to speed up AT processing 2020-10-06 14:09:42 +01:00
catbref
a2038274e1 Keep latest AT state, even if "finished", so we can produce historical trade data 2020-10-05 15:18:41 +01:00
catbref
532c697026 Moved AT State & online signatures trimming intervals, batch sizes, limits, etc. to Settings 2020-10-02 12:58:23 +01:00
catbref
5cf5c1e1f7 Take pressure off GC by not creating/destroying HSQLDB sub-repositories all the time 2020-10-01 13:18:24 +01:00
catbref
60621e8b81 Reworked AT-states and online signatures trimming
Instead of searching from block 0, we now keep a record of
base trim height in the DB itself.

Also, we no longer trim the latest AT state for non-finished ATs
in case they are in deep sleeping and we need their state for when
they awaken.
2020-10-01 13:17:00 +01:00
catbref
a6a1f65d3e Reduce block search size in AT state trimmer to reduce load 2020-09-29 11:41:30 +01:00
catbref
a681f741dd Add initial delay before trimming online accounts signatures 2020-09-29 11:40:41 +01:00
catbref
bed9837967 Added settings entry "localeLang" for controlling core language (not-API) 2020-09-29 10:56:27 +01:00
catbref
855cb2226a Aggressively trim old AT state data and online accounts signatures.
Two new classes/threads made to quickly find first trimmable row
then repeatedly trim rows in small batches after that.
2020-09-28 14:34:00 +01:00
catbref
d85a3d17c8 Fix for HSQLDB deadlock during CHECKPOINT.
Symptoms are:

* db/blockchain.log is pretty much exactly 50MB - the checkpoint-triggering size.

* Loads of threads are stuck waiting for HSQLDB's CountUpDownLatch$Sync.await()

* Synchronizer, or some other thread, possibly orphaning blocks.

The cause seems to be method A, which has a repository session,
calls EventBus.INSTANCE.notify() and one of the event listeners
then obtains their own repository session to do repository 'work'.

In the meantime, the HSQLDB log has reached 50MB, triggering auto-checkpoint.

HSQLDB attempts to CHECKPOINT, but waits for existing transactions
to complete, and also blocks starting new transactions.

Thus, one of the event listeners is blocked when they try to obtain
a new repository session, but HSQLDB never performs CHECKPOINT
because the event notifier (method A) still has an unfinished
transaction - hence deadlock.
2020-09-28 14:22:18 +01:00
catbref
81a5b154c2 Add API call DELETE /admin/repository which actually performs repository maintenance (takes several minutes) 2020-09-25 17:06:06 +01:00
catbref
a6f42df9d6 Add isTestNet to API call GET /admin/info 2020-09-25 16:35:53 +01:00
catbref
17ae7acc6d Reduce DB storage of AT states
Drop created_when column from ATStates as it never changes
and can be fetched from ATs table.
This takes about 50s on a fast machine.

Correspondingly rebuild height-based index on ATStates.
This takes about 3 minutes on a fast machine.

Modify AT-related repository methods and callers.

Aggressively remove 'old' (> 2 weeks) actual AT
state binary data, leaving only the hash in DB
(for syncing purposes). Seems to keep up with
syncing from another node on localhost.
2020-09-25 15:25:57 +01:00
catbref
21f48fba5f HSQLDB PreparedStatement caching improvements 2020-09-24 12:46:30 +01:00
catbref
d0da5d7c48 ATs: only call MachineState.getCodeBytes() once in preparation for using newer AT lib 2020-09-24 12:46:17 +01:00
catbref
4209cc6ee4 Improve SQL prepared statement caching in HSQLDBATRepository, plus missing space in SQL in getMatchingFinalATStates 2020-09-23 09:41:24 +01:00
catbref
f3e1092dd5 Improve SQL prepared statement caching in HSQLDBBlockRepository.getBlockInfos & test to cover 2020-09-23 09:40:41 +01:00
catbref
43055b666f Improve SQL prepared statement caching in HSQLDBAccountRepository.getEligibleLegacyQoraHolders() 2020-09-23 09:38:08 +01:00
catbref
7cd8ed6e23 HTLC secret and status caching to reduce repeated calls to ElectrumX network
Additional benefit is to speed up syncing if node has trade-bot entries,
as a batch of blocks processed within 30s will have the same HTLC responses
as neither Bitcoin nor Litecoin blocks are that fast. Once synced, the next
Qortal block (~60s) should pick up any new changes. Generally users will be
synced when using trade-bot anyway.

Also moved bitcoiny.getAddressTransactions(p2shAddress)
into BitcoinyHTLC.findHtlcSecret() so only called if secret,
or lack thereof, is not cached.

Added tests to cover caching.
2020-09-22 12:13:22 +01:00
catbref
4bc0edeeca Litecoin trade-bot added!
Several cross-chain API calls moved into separate classes,
although most of the URLs remain roughly the same to provide
backwards compatibility.

API /crosschain/at/build moved into /crosschain/BitcoinACCTv1

Converted DELETE /crosschain/tradeoffer to be ACCT-agnostic.
Changes to ACCT interface, etc. to support above.

Changes applied to other crosschain API calls to make them
independent of Bitcoin/Litecoin.

Corrections to fee calculations and usage in BitcoinACCTv1.

Added new LitecoinACCTv1 trade-bot, using LitecoinACCTv1.

Some minor typo corrections, rename of secretHash to hashOfSecret.

Some more Bitcoin-specific fields deprecated, but values duplicated
from newly-named fields for now.

Lower default fee (10sats/byte) for Litecoin spending transactions.
(Not P2SH fees which are 1000sats).

Changed ApiError INSUFFICIENT_BALANCE HTTP status from 422 to 402
as 422 isn't supported by Jetty?

CrossChainTradeSummary.btcAmount deprecated, use: foreignAmount

Modified pom.xml to generated package-info.java files for classes
inside org.qortal.api.model.** subdirectories.
2020-09-21 16:54:43 +01:00
catbref
7a06df6ccd Improve SQL prepared statement caching in HSQLDBATRepository, plus missing space in SQL in getMatchingFinalATStates 2020-09-21 16:42:43 +01:00
catbref
d9164a32e5 Improve SQL prepared statement caching in HSQLDBBlockRepository.getBlockInfos & test to cover 2020-09-21 16:38:45 +01:00
catbref
a8fbf32a88 Improve SQL prepared statement caching in HSQLDBAccountRepository.getEligibleLegacyQoraHolders() 2020-09-21 16:29:34 +01:00
catbref
514689d2f4 WIP: refactoring to support multiple foreign blockchains
API support for Litecoin wallet balance and sending LTC.

TradeBotCreateRequest rejigged to use blockchain-agnostic
field names, e.g. bitcoinAmount now foreignAmount,
and added foreignBlockchain field.

The massive API CrossChainResource class has been split into:

CrossChainAtResource: for building TRADE/REDEEM/CANCEL messages
(OFFER missing?)

CrossChainBitcoinResource: for Bitcoin wallet balance/spend
CrossChainLitecoinResource: ditto for Litecoin

CrossChainHtlcResource: for Bitcoiny-HTLC actions like:
deriving P2SH address
checking HTLC status
eventually: building refund/redeem transactions

CrossChainResource: for creating/cancelling/listing trade offers.

CrossChainTradeBotResource: for creating/cancelling trade-bot
entries, including responding to trade offers.

---

Other general trading changes:

TradeBot states are now specific to each individual trade-bot,
e.g. BitcoinACCTv1TradeBot or LitecoinACCTv1TradeBot, etc.

TradeBot states now a combination of int & String, instead of
enums due to above.

Extra columns added to DB TradeBotStates to store
blockchain, which ACCT in use, etc.

---

UNTESTED at this point!
2020-09-18 17:07:49 +01:00
catbref
76a15bb026 Initial implementation of Litecoin ACCT
Extracted AcctMode from BitcoinACCTv1.Mode as the values are
common to both Bitcoin/Litecoin ACCTs.

Added test apps for deploy, cancel, trade and redeem of LitecoinACCTv1.
2020-09-17 11:07:07 +01:00
catbref
b061f188f9 Update Bitcoinv1 DeployAT test app 2020-09-16 11:11:18 +01:00
catbref
af7d7d0966 Unified Bitcoin/Litecoin test apps 2020-09-16 10:57:45 +01:00
catbref
2ffd0770c6 Initial Litecoin support
Added altcoinj library as Maven dependency.

Added new Litecoin subclass of Bitcoiny,
with mainnet and testnet ElectrumX server lists.

Added litecoinNet settings variable and getter.

Added LitecoinTests.
Most tests work but testFindHtclSecret()
needs a redeemed HTLC on chain (not yet done).

Added litecoinNet to some test settings files
in resources.

Added Litecoin BuildHTLC, Refund test apps.

Added SendLTC app as Electrum-LTC seems a bit flaky?

So far managed to build HTLC P2SH, fund it and then
refund it!

---

As Bitcoin and Litecoin are both subclasses of Bitcoiny,
could unify some test apps with added Bitcoin/Litecoin
switch as first arg?
2020-09-15 17:53:54 +01:00
catbref
e3abeafc6b Refactoring to allow many foreign blockchains and multiple ACCTs
Bitcoin/Litecoin common aspects extracted in a "Bitcoiny" common class.
So:

Bitcoin (was BTC) extends Bitcoiny
Litecoin (future code) will also extend Bitcoiny

ElectrumX is now a BitcoinyBlockchainProvider
to allow easier future replacement and also tidier integration.

BTCP2SH is now BitcoinyHTLC as they are generic hash time-locked contracts,
probably Bitcoin/Litecoin agnostic.

BTCACCT is now BitcoinACCTv1, allowing for v2+ and also LitecoinACCTv1, etc.

BitcoinTransaction is now BitcoinyTransaction
as they are pretty much the same in Litecoin.

BitcoinException is now a more generic ForeignBlockchainException.

---

Bitcoiny subclasses instantiate a new BitcoinyBlockchainProvider
when creating their singleton instance. They pass relevant network
details to the BBP, like server lists, genesis block hash, etc.

Bitcoiny.WalletAwareUTXOProvider now only has the one key search mode
that is equivalent to the old REQUEST_MORE_IF_ANY_SPENT.

Tests tidied up.

---

Still to do:

Modifying TradeBot to handle multiple types of ACCTs,
like BitcoinACCTv2, LitecoinACCTv1...

Modifying API to support multiple types of ACCTs.

Actually add Litecoin support.

Build new ACCT without needing P2SH-B if possible.
2020-09-15 14:56:43 +01:00
catbref
1720582f33 Remove obsolete NextBlockHeight table and corresponding triggers
Also fix typo in Block.online_accounts varbinary size.
2020-09-11 16:06:53 +01:00
catbref
d93e9d570f Trimming old block online accounts signatures
There's still an existing issue where log entries like this appear:

  Unable to trim old online accounts signatures in repository

which is actually caused by:

  integrity constraint violation: unique constraint or index violation; SYS_PK_10092 table: BLOCKS

which seems to be a bug in the version of HSQLDB we use.
(Tested using synced-from-scratch DB).
It's not clear what the actual problem is at this point.

It might be possible to switch to v2.5.1 if our recent HSQLDB-related
commits have fixed/worked-around the OOM issues.

Move the inner method from BlockChain to Controller.
Remove blockchain lock as it's not needed because it's not an
HSQLDB "serialization failure" but constraint violation.

Trimming old online accounts signatures limited to batches of 1440
rows to reduce CPU and memory load.
2020-09-11 15:57:12 +01:00
catbref
5ea90f2fdd Speed up fetching transactions using block signature 2020-09-11 15:56:19 +01:00
catbref
c628f97d8c Speed up fetching block height based on timestamp 2020-09-11 15:55:54 +01:00
catbref
8a1e2f4111 Reduce HSQLDBRepository log noise by omitting idle session info 2020-09-11 15:54:32 +01:00
catbref
41f244d549 Add bitcoinj Context propagation 2020-09-11 15:52:59 +01:00
catbref
79641efa87 Tighten up trade-bot, ElectrumX
Added separate method to determine status of P2SH transactions,
returning UNFUNDED, FUNDING_IN_PROGRESS, REDEEMED, etc.

Added code to trade-bot to increase robustness. Lots more
changes including unified state change/logging, checking
for existing MESSAGEs, etc.

Added missing websocket methods to silence log noise.

Trade-bot now called per block during synchronization,
instead of per batch, to pick up edge cases where some
potential trade-bot transitions were missed, resulting
in failed trades.

Corresponding changes in Controller, such as notifying
event bus of new block in same thread (thus blocking)
instead of using executor.

Added slightly more robust common block determination
to Synchronizer.

Refactored code in BTC class to use new BitcoinException
rather than simply returning null, with added sub-classes
allowing differentiation between network issues or fund
issues.

Changed BTC.buildSpend to try harder to find UXTOs to
address false "insufficient funds" issues.

Repository change to add index on MessageTransactions
for quicker look-up of trade-related messages.

Reduced reliance on bitcoinj library in BTCP2SH.

Reworked ElectrumX to better detect errors rather than
continuously try more servers to no avail.
Also added genesis block check in case of servers on
different Bitcoin networks.
Now tries to extract upstream bitcoind error codes
and pass those up to caller via exceptions.
Updated list of testnet servers.

MemoryPoW now detects thread interrupt and exits fast.

Moved some non-generic transaction-related repository
methods to their own subclass. For example:
moved TransactionRepository.getMessagesByRecipient
to MessageRepository.getMessagesByParticipants

Updated and added more tests.
2020-09-10 12:03:37 +01:00
catbref
ca3fcc3c67 Tighten up sync status reporting, especially when using forcesync 2020-09-03 12:57:29 +01:00
catbref
3cc66609e8 Trial implementation of offline repository periodic maintenance.
Requires node shutdown, lots of time (10s of minutes), spare storage space.
Called via: java -cp qortal.jar org.qortal.RepositoryMaintenance
Not (yet) for general consumption.
2020-08-31 11:51:38 +01:00
catbref
ce468d22dd Fix updating of current tradeoffers list as used by tradeoffers websocket 2020-08-31 11:25:21 +01:00
catbref
3e19516f62 Correct poor synchronization on NTP offset, potentially fixing issue #22 2020-08-31 10:24:10 +01:00
catbref
84dba739d9 Give up on cross-chain trade if initial AT doesn't confirm within 24 hours 2020-08-31 09:21:15 +01:00
catbref
99315c7378 Correct wrong source for lockTimeA when Bob waiting for P2SH-B. Spotted by tcallahan14. In lieu of PR #23 2020-08-31 09:14:15 +01:00
catbref
1ca5b864a9 Repository optimizations!
Added Qortal-side HSQLDB PreparedStatement cache, hashed
by SQL query string, to reduce re-preparing statements.
(HSQLDB actually does the work in avoiding re-preparing
by comparing its own query-to-statement cache map, but we
need to keep an 'open' statement on our side for this to
happen).

Support added for batched INSERT/UPDATE SQL statements to
update many rows in one call.

Several specific repository calls, e.g. modifyMintedBlockCount
or modifyAssetBalance, now have batch versions that allow
many rows to be updated in one call.

In Block, when distributing block rewards, although we still
build a map of balance changes to apply after all calculations,
this map is now handed off wholesale to the repository to
apply in one (or two) queries, instead of a repository call
per account. The balanceChanges map is now keyed by account
address, as opposed to actual Account.

Also in Block, we try to cache the fetched online reward-shares
(typically in Block.isValid et al) to avoid re-fetching them
later when calculating block rewards.

In addition, actually fetching online reward-shares is no longer
done index-by-index, but the whole array of indexes is passed
wholesale to the repository which then returns the corresponding
reward-shares as a list.

In Block.increaseAccountLevels, blocks minted counts are also
updated in one single repository call, rather than one
repository call per account.

When distributing Block rewards to legacy QORA holders,
all necessary info is fetched from the repository in one hit
instead of two-phases of: 1. fetching eligible QORA holders,
and 2. fetching extra data for that QORA holder as needed.

In addition, updated QORT_FROM_QORA asset balances are done
via one batch repository call, rather than per update.
2020-08-26 17:16:45 +01:00
catbref
96eb60dca3 More HSQLDB tests to cover fixes for various HSQLDB issues, especially when using custom HSQLDB build 2020-08-25 17:02:14 +01:00
catbref
5952ea4b54 RU translations thanks to Alexander45 2020-08-24 15:04:33 +01:00
catbref
1708ba077c Actually define static constants for BTC fees until dynamic fees happen 2020-08-24 14:28:54 +01:00
catbref
b4301f125d Potential fix for issue #22 2020-08-24 14:27:03 +01:00
catbref
31bf388cab BlockMinter (now under org.qortal.controller package) doesn't need full previous block, only previous block data 2020-08-24 14:04:11 +01:00
catbref
276c479a5f Refactor to allow better Bitcoin fee estimation in the future. 2020-08-21 17:37:04 +01:00
catbref
9393689037 Send BTCACCT refunds to first unused received address instead of address derived from tradePrivateKey.
Added BTC.getUnusedReceiveAddress() to support above.
2020-08-21 17:35:33 +01:00
catbref
76485010ad
Merge pull request #16 from tcallahan14/feature/electrum_nodes
Updated Electrum nodes list
2020-08-21 13:34:49 +01:00
catbref
b8ac128d5c Improve comparing chains where some blocks signed with cancelled reward-share
Symptoms include this in logs:

Unexpected zero effective minter level for reward-share %s - using 1 instead!

This occurs when Synchronizer compares two sub-chains from a common block,
and one of the blocks is signed by a reward-share key that has
subsequently been cancelled.

Although this is catered for, excessive log-spam is emited.

So in addition to demoting the log level from WARN to DEBUG,
more code has been added to try harder to find the actual data needed,
thus preventing the logging in the first place.

New repository transaction search method added to support above,
along with corresponding tests.
2020-08-21 12:27:06 +01:00
CalDescent
06c75310a1 Updated Electrum nodes list. All nodes have been tested to ensure they respond to jsonrpc calls. 2020-08-15 16:53:09 +01:00
catbref
b9d819220d Bumped HSQLDB to v2.5.1 and AT/cross-chain SQL speed-ups! 2020-08-15 11:12:10 +01:00
catbref
7a569f342f Reduce confusing BlockMinter log spam - issue #9 2020-08-15 10:52:48 +01:00
catbref
f1efae79c8 Speed-ups for some AT-related SQL queries 2020-08-14 11:54:33 +01:00
catbref
1cd4bbc078 Refactored various websockets to event bus from old BlockNotifier/StatusNotifier 2020-08-14 10:03:51 +01:00
catbref
0b5e5832c4 Added another repository deadlock test while investigating a deadlock case 2020-08-14 09:57:08 +01:00
catbref
f8725d6313 Modify ApplyUpdate to pass JVM options to Windows launcher EXE
ApplyUpdate is the 2nd-stage of the auto-update system, called
after core has downloaded the update.

As old versions of the Windows launcher EXE selects a 'client'
JVM mode, heap memory could be limited to only 256MB.

Until users upgrade via Windows installer, which replaces the EXE
with 'server' JVM mode baked-in, then a work-around is to
pass -XX:MaxRAMFraction=4 to the new JVM in order to emulate
heap size in 'server' JVM mode.
2020-08-13 14:08:47 +01:00
catbref
2165c87b9d Fix race condition between Network.start() and Controller calling Network.prunePeers()
Modified synchronized Lists to be final.
Moved some initializers out of constructor.
2020-08-13 13:45:06 +01:00
catbref
f61e320230 Fix API call GET /crosschain/trades (get completed trades) due to poorly performing SQL query.
Added "minimumTimestamp" param to same API call to allow fetching results for scenarios like:
* completed trades since midnight
* completed trades within last 24 hours

Added corresponding tests for above API call, including checking call response times.
2020-08-13 11:56:08 +01:00
catbref
f6216b9745 Respect repositoryBackupInterval when deciding whether to perform backup during auto-update. Issue #10 2020-08-12 14:22:36 +01:00
catbref
91e82d1e3c Add HSQLDB CHECKPOINT statements between database reshaping statements to reduce failures 2020-08-12 14:20:23 +01:00
catbref
50e2bda020 Quicken blockchain validity check at start-up by only checking most recent 1440 blocks 2020-08-12 14:19:14 +01:00
catbref
ab1de1aafa Improve HSQLDB query for finding latest AT state data 2020-08-12 14:18:05 +01:00
catbref
d4ac87f91d Update to more efficient CIYAM AT v1.3.7 2020-08-12 14:17:09 +01:00
catbref
d8dd71ff50 Fix off-by-one in some sync cases 2020-08-10 15:22:01 +01:00
catbref
02966bf39a Update CIYAM-AT to v1.3.6 to make use of lambda-based logging 2020-08-10 14:05:42 +01:00
catbref
a83d8bf1d5 Split Synchronizer into two strategies depending on whether swapping chains or simply adding new blocks 2020-08-10 14:00:45 +01:00
catbref
1e4432b1f3 Convert LOBs to VARBINARY in DB, reducing sizes at the same time 2020-08-10 13:59:56 +01:00
catbref
d50c979d9f Tighten limit on AT sizes 2020-08-10 13:59:20 +01:00
catbref
4e60ec5192 Disable peer buffer dealloc for now to reduce GC pressure 2020-08-10 13:58:12 +01:00
catbref
31c4e3b1be Reduce memory PoW during network handshake 2020-08-10 13:57:16 +01:00
catbref
b97fbd3171 Bug-fix for cached online accounts 2020-08-07 16:19:32 +01:00
catbref
43fb5d9332 Cache top 2 blocks' worth of online account data to avoid unnecessary Ed25519 verifications 2020-08-07 13:33:31 +01:00
catbref
ea3f1a8eff Actually respond to peers requesting unknown block instead of letting them timeout on their side 2020-08-07 13:32:19 +01:00
catbref
a1ab0b7c31 Added more nodes to initial list 2020-08-06 15:38:52 +01:00
catbref
fae2afd010 Remove obsolete github repo from potential auto-update sites 2020-08-06 15:23:13 +01:00
catbref
76c0a5a4fa Increase default Bitcoin transaction fee to 5000 sats 2020-08-06 13:12:54 +01:00
catbref
cdb65657b6 Added qortal.ru nodes to initial nodes list used when creating DB 2020-08-06 09:51:14 +01:00
catbref
9007dfe779 Added API call POST /crosschain/btc/send for sending Bitcoin 2020-08-06 09:46:08 +01:00
catbref
99d09a9877 Change HTTP response codes for BTC_BALANCE_ISSUE and BTC_TOO_SOON from 422 to 402 & 408 2020-08-06 09:45:38 +01:00
catbref
afcf51399e Minor post-merge fix-up 2020-08-06 09:18:08 +01:00
catbref
47679b7f6c Merge branch 'trade-bot' 2020-08-06 09:00:45 +01:00
catbref
8f2985862d Update BTC-ACCT 'cancel' API call to expect AT creator's as sender 2020-08-06 08:52:51 +01:00
catbref
23a524b464 BTC-ACCT: change AT so 'cancel' MESSAGE needs to come from AT creator's address (not trade address) so fee can be used instead of PoW for faster cancels 2020-08-06 08:23:49 +01:00
catbref
ce8992867d Include last 24 hours of CANCELLED & REFUNDED trade offers in first message 2020-08-05 20:58:25 +01:00
catbref
c89de7adfb Add creatorAddress, qortAmount and (last updated) timestamp to trade-bot entries 2020-08-05 16:00:40 +01:00
catbref
cac68ccc14 Added trade-bot websocket 2020-08-05 13:23:24 +01:00
catbref
d507383487 Rework ApiWebSocket so it can manage sessions and in readiness to conversion from "notifiers" to event-bus 2020-08-05 13:23:07 +01:00
catbref
ce5cf87094 Added unified, simple event bus to eventually replace controller "notifiers" 2020-08-05 13:20:19 +01:00
catbref
ec2c9d2a44 Improve /crosschain/tradebot/respond with varied API errors such as BTC_BALANCE_ISSUE, BTC_NETWORK_ISSUE, etc. instead of just "false" 2020-08-05 10:05:09 +01:00
catbref
36d0abe635 WIP: trade-bot: log warning when we can't fund P2SH-B for some reason 2020-08-05 10:04:25 +01:00
catbref
615381ca5a Fix BTC spend txn building to be less aggressive about caching/checking spent keys 2020-08-05 10:03:08 +01:00
catbref
6b83499216 WIP: trade-bot: add support for showing trade partner's Qortal receiving address in trade offer summaries 2020-08-04 20:35:22 +01:00
catbref
faa2e9502b WIP: trade-bot: include creation/latest timestamp (as appropriate) in trade offer summaries via websocket 2020-08-04 17:00:36 +01:00
catbref
cd07240ce7 Add BTC.getWalletBalance(xprv) and add API call to access that.
Also improved BTC.WalletAwareUTXOProvider to derive more keys itself
instead of throwing and relying on caller to do the work.
Added benefit of cleaning up caller code and being more efficient.
Needed because not all receiving/change addresses were being picked up.
2020-08-04 16:37:44 +01:00
catbref
91518464c2 WIP: trade-bot: fix empty bitcoin wallet edge case when finding UTXOs 2020-08-04 12:26:09 +01:00
catbref
25bf315e23 WIP: trade-bot: tradeoffers websocket initial message with OFFERING/REDEEMED and fixed subsequent messages 2020-08-04 11:21:57 +01:00