forked from bitcoinafterlife/bal-electrum-plugin
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ce42d6f12 | ||
|
|
014dd230c1 | ||
|
|
2054e4f4b2 | ||
|
|
ae7ea24bdf | ||
|
|
06c32268a7 | ||
|
|
6fb82dc8d0 | ||
|
|
9c91cc8019 | ||
|
|
5dc1ca36ab | ||
|
|
694e14d851 | ||
|
|
60fc08ad5a | ||
|
|
22fa6cd708 | ||
|
|
b63dc5ba4f | ||
|
|
a5f6b9f925 | ||
|
|
c739d110d6 | ||
|
d439b1fdde
|
|||
|
c99f0fd70f
|
|||
|
ab6aa7a698
|
|||
|
b55493221d
|
|||
|
|
45d8173cf7 | ||
|
|
b739bdab40 | ||
|
|
d613438800 | ||
|
|
a27df11dfa | ||
|
|
686c11080f | ||
|
|
be38c9b589 | ||
|
dff508c25b
|
|||
|
2056ffae7f
|
|||
|
c8ab85b735
|
|||
|
e2de4a3afa
|
|||
|
3a44b492e4
|
|||
|
9737221914
|
359
README.md
359
README.md
@@ -1,2 +1,357 @@
|
||||
# BalPlugin
|
||||
Bitcoin After Life Electrum Plugin
|
||||
# Bal Electrum Plugin
|
||||
|
||||
⚡ **Bitcoin Electrum plugin for managing heir inheritance with locktime-based will execution**
|
||||
|
||||
---
|
||||
|
||||
## 📥 Installation
|
||||
|
||||
### Method 1: Install from Release (Recommended)
|
||||
|
||||
1. **Download the plugin**
|
||||
- Go to: [https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/releases](https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/releases)
|
||||
- Download the latest `bal-electrum-plugin-vX.X.X.zip` file
|
||||
|
||||
2. **Install in Electrum**
|
||||
- Open Electrum Bitcoin wallet
|
||||
- Go to **Tools → Plugins**
|
||||
- Click **Add**
|
||||
- Select the downloaded `.zip` file
|
||||
- Click **Open** or **Install**
|
||||
- Restart Electrum if required
|
||||
|
||||
### Method 2: Install from Source
|
||||
|
||||
```bash
|
||||
git clone https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin.git
|
||||
cd bal-electrum-plugin
|
||||
zip -r bal-electrum-plugin.zip bal_electrum_plugin/
|
||||
```
|
||||
|
||||
Then install using Method 1, step 2.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 How It Works
|
||||
|
||||
### Core Functionality
|
||||
|
||||
The plugin allows users to create a **Bitcoin will** that automatically executes under specific conditions:
|
||||
|
||||
1. **Define Heirs** - Create a list of beneficiaries with Bitcoin addresses and inheritance amounts
|
||||
2. **Set Locktime** - Configure when transactions can be spent (timestamp or interval)
|
||||
3. **Set CheckAlive** - Set health verification mechanism (interval or fixed date)
|
||||
4. **Select Executor** - Choose which will-executor will handle the transaction
|
||||
5. **Create Transaction** - Plugin generates a timelocked transaction sent to the executor
|
||||
|
||||
### Transaction Flow
|
||||
|
||||
```
|
||||
User Setup → [Plugin Creates Transaction] → Executor Receives →
|
||||
Executor Broadcasts at Locktime → Transaction Confirmed → Heirs Receive Funds
|
||||
```
|
||||
|
||||
### Key Incentive
|
||||
|
||||
**Executor Fee is Included in Transaction**:
|
||||
- The will-executor receives their fee directly in the transaction output
|
||||
- Fee is paid only when transaction is confirmed on the Bitcoin network
|
||||
- Executor is **financially incentivized** to broadcast and confirm the transaction
|
||||
- Fee is a **fixed amount only** (no percentage option)
|
||||
|
||||
---
|
||||
|
||||
## 📁 Plugin Structure
|
||||
|
||||
```
|
||||
bal-electrum-plugin/
|
||||
├── bal_electrum_plugin/ # Main plugin directory (what to zip)
|
||||
│ ├── __init__.py # Plugin initialization and entry point
|
||||
│ ├── bal.py # Main plugin logic and core functionality
|
||||
│ ├── bal_resources.py # Resource management and asset handling
|
||||
│ ├── heirs.py # Heir management logic and validation
|
||||
│ ├── qt.py # Main Qt interface and GUI components
|
||||
│ ├── util.py # General utility functions
|
||||
│ ├── wallet_util/
|
||||
│ │ ├── bal_wallet_utils.py # ⚠️ Advanced wallet utilities for emergency fixes
|
||||
│ │ └── bal_wallet_utils_qt.py # Qt-specific wallet utilities
|
||||
│ ├── will.py # Will creation, locktime, and checkalive logic
|
||||
│ └── willexecutors.py # Will executor management and fee handling
|
||||
├── README.md # This file
|
||||
└── LICENSE # MIT License
|
||||
```
|
||||
|
||||
**Important**: Only the `bal_electrum_plugin/` directory needs to be zipped for installation.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Features
|
||||
|
||||
### Heir Management (heirs.py)
|
||||
- **Multiple heirs**: Add unlimited beneficiaries
|
||||
- **Flexible distribution**: Percentage-based or fixed amount
|
||||
- **Address validation**: Verify Bitcoin addresses before saving
|
||||
- **Distribution summary**: View total inheritance breakdown
|
||||
- **Percentage validation**: Ensures percentages sum to 100%
|
||||
|
||||
### Locktime Configuration (will.py)
|
||||
- **Timestamp format**: Unix timestamp (e.g., `1735689600` for Jan 1, 2025)
|
||||
- **Interval format**: Days (`180d`) or years (`1y`)
|
||||
- **Automatic conversion**: Intervals converted to timestamps internally
|
||||
- **Validation**: Ensures locktime is in the future
|
||||
- **Flexible timing**: Set exact date or relative intervals
|
||||
|
||||
### CheckAlive Mechanism (will.py)
|
||||
- **Two verification modes**:
|
||||
|
||||
**Interval Mode**:
|
||||
- Format: Same as locktime (e.g., `180d`, `2y`)
|
||||
- Logic: `locktime - interval > current_time`
|
||||
- Example: Locktime=1y, CheckAlive=180d → Valid if 365-180 > current days
|
||||
|
||||
**Fixed Date Mode**:
|
||||
- Format: Timestamp
|
||||
- Logic: `fixed_date > current_time`
|
||||
- Example: CheckAlive=2025-12-31 → Valid if date is in the future
|
||||
|
||||
- **Effect**: If CheckAlive expires, the old will is invalidated
|
||||
- **Safety mechanism**: Prevents stale wills from executing
|
||||
|
||||
### Will Executor System (willexecutors.py)
|
||||
- **Multiple executors**: Choose from available executors
|
||||
- **Fixed fee only**: Executor receives a fixed BTC amount (no percentage option)
|
||||
- **Fee included in transaction**: Fee is part of the timelocked transaction output
|
||||
- **Financial motivation**: Executor must broadcast to get paid
|
||||
- **Automatic transmission**: Transaction sent to executor after creation
|
||||
- **Blockchain monitoring**: Executor broadcasts at locktime expiration
|
||||
|
||||
**Executor Fee Details**:
|
||||
- Fee is specified as fixed BTC amount only
|
||||
- Fee is added to transaction outputs
|
||||
- Executor receives fee only when transaction confirms
|
||||
- No separate payment channel needed
|
||||
|
||||
### Advanced Wallet Utilities (wallet_util/)
|
||||
- **⚠️ Emergency tools only**: For fixing wallet database issues
|
||||
- **Purpose**: Handle compatibility across different Electrum walletdb versions
|
||||
- **Usage**: Advanced users only, requires manual installation
|
||||
- **Installation Steps**:
|
||||
1. Copy `wallet_util/` files to Electrum's plugin directory
|
||||
2. Load Electrum's virtualenv
|
||||
3. Run `./bal_wallet_utils_qt.py`
|
||||
|
||||
- **Risk**: Advanced operations that can affect wallet data
|
||||
- **Documentation**: Limited to inline code comments
|
||||
|
||||
**Normal operation does NOT require wallet_util/ files.**
|
||||
|
||||
### Main Interface (qt.py)
|
||||
- **User-friendly wizards**: Step-by-step setup interface
|
||||
- **Real-time validation**: Immediate feedback on inputs
|
||||
- **Transaction preview**: Review before finalizing
|
||||
- **Status monitoring**: Track will execution progress
|
||||
- **Error handling**: Clear messages for invalid inputs
|
||||
|
||||
---
|
||||
|
||||
## 📖 Usage Examples
|
||||
|
||||
### Example 1: Simple Inheritance Will
|
||||
|
||||
**Scenario**: Leave 1 BTC to three heirs after 1 year, with 180-day CheckAlive
|
||||
|
||||
**Configuration**:
|
||||
```
|
||||
Heirs:
|
||||
- Heir 1: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq - 40% (0.4 BTC)
|
||||
- Heir 2: bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4 - 35% (0.35 BTC)
|
||||
- Heir 3: bc1ql4wk3ym38m8p3kns5w5q4tech38x58s3yy263q - 25% (0.25 BTC)
|
||||
|
||||
Locktime: 1y (1 year from now)
|
||||
CheckAlive: 180d (180 days before locktime)
|
||||
Executor: "Alice Executor" (fee: 0.01 BTC fixed)
|
||||
```
|
||||
|
||||
**Transaction Created**:
|
||||
- Input: All UTXOs in wallet (1.0 BTC total)
|
||||
- Outputs:
|
||||
- Heir 1: 0.4 BTC
|
||||
- Heir 2: 0.35 BTC
|
||||
- Heir 3: 0.25 BTC
|
||||
- Executor fee: 0.01 BTC (fixed amount)
|
||||
- Network fee: 0.001 BTC
|
||||
- Locktime: 1 year from creation
|
||||
- Sent to: Alice Executor's address
|
||||
|
||||
**Executor Incentive**:
|
||||
- Alice receives 0.01 BTC **only if** she broadcasts and transaction confirms
|
||||
- Alice has financial motivation to ensure transaction is confirmed
|
||||
- Transaction cannot be spent until locktime expires
|
||||
|
||||
### Example 2: Fixed Date CheckAlive
|
||||
|
||||
**Scenario**: Leave funds with CheckAlive on specific date
|
||||
|
||||
**Configuration**:
|
||||
```
|
||||
Locktime: 2026-06-01 (timestamp: 1748832000)
|
||||
CheckAlive: 2025-12-31 (timestamp: 1767187200)
|
||||
Heirs: 50% to heir1, 50% to heir2
|
||||
Executor: "Bob Executor" (fee: 0.005 BTC fixed)
|
||||
```
|
||||
|
||||
**Logic**:
|
||||
- If today > 2025-12-31 → Old will is invalid
|
||||
- If old will is invalid, a non-timelocked transaction is sent onchain to invalidate the old will
|
||||
- Transaction executes on 2026-06-01
|
||||
- Bob receives 0.005 BTC only when transaction confirms
|
||||
- Bob is incentivized to broadcast at correct time
|
||||
|
||||
### Example 3: Complex Distribution with Fixed Amounts
|
||||
|
||||
**Scenario**: Leave different fixed amounts to heirs
|
||||
|
||||
**Configuration**:
|
||||
```
|
||||
Heirs:
|
||||
- Heir 1: bc1... - 0.3 BTC (fixed amount)
|
||||
- Heir 2: bc1... - 0.5 BTC (fixed amount)
|
||||
- Heir 3: bc1... - 0.2 BTC (fixed amount)
|
||||
|
||||
Total: 1.0 BTC
|
||||
Locktime: 365d (1 year from now)
|
||||
CheckAlive: 180d (6 months before locktime)
|
||||
Executor: "Charlie Executor" (fee: 0.02 BTC fixed)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Prerequisites
|
||||
- Electrum Bitcoin wallet
|
||||
|
||||
### Setup Development Environment
|
||||
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin.git
|
||||
cd bal-electrum-plugin
|
||||
|
||||
# Create development zip
|
||||
zip -r bal-electrum-plugin-dev.zip bal_electrum_plugin/
|
||||
```
|
||||
|
||||
### Important Notes on wallet_util/
|
||||
|
||||
**These utilities require manual installation**:
|
||||
|
||||
- **Purpose**: Fix wallet database compatibility issues across Electrum versions
|
||||
- **Usage**: Only when experiencing wallet corruption or version mismatches
|
||||
- **Installation Steps**:
|
||||
1. Copy `wallet_util/` files to Electrum's plugin directory
|
||||
2. Load Electrum's virtualenv
|
||||
3. Run `./bal_wallet_utils_qt.py`
|
||||
|
||||
- **Risk**: Advanced operations that can affect wallet data
|
||||
- **Documentation**: Limited to inline code comments
|
||||
|
||||
**Normal operation does NOT require wallet_util/ files.**
|
||||
|
||||
### Install for Development
|
||||
|
||||
1. Copy zip to Electrum plugins directory:
|
||||
```bash
|
||||
cp bal-electrum-plugin-dev.zip ~/.electrum/plugins/
|
||||
```
|
||||
|
||||
2. Install in Electrum (Tools → Plugins → Add)
|
||||
|
||||
3. Make changes to files in `bal_electrum_plugin/` directory
|
||||
|
||||
4. Re-zip and reinstall to test
|
||||
|
||||
### Running the Plugin
|
||||
|
||||
The plugin uses Electrum's existing virtualenv.
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Plugin Not Showing in Electrum
|
||||
- ✅ Check zip contains `bal_electrum_plugin/` directory at root
|
||||
- ✅ Verify directory structure inside zip is correct
|
||||
- ✅ Restart Electrum completely after installation
|
||||
- ✅ Check Electrum logs: Help → Debug → Console
|
||||
|
||||
#### Locktime Format Errors
|
||||
- ✅ Use valid formats: `180d`, `1y`, or Unix timestamp (e.g., `1735689600`)
|
||||
- ✅ Ensure locktime is in the future (after current time)
|
||||
- ✅ Check for typos: lowercase `d` and `y` only
|
||||
- ✅ Verify interval calculations: `1y` = 365 days
|
||||
|
||||
#### CheckAlive Not Working
|
||||
- ✅ Verify CheckAlive mode setting (interval or fixed_date)
|
||||
- ✅ Ensure CheckAlive value is before Locktime value
|
||||
- ✅ For interval mode: Check logic `locktime - interval > now`
|
||||
- ✅ For fixed date: Verify timestamp is in the future
|
||||
- ✅ If CheckAlive expires, old will is invalidated by sending a non-timelocked transaction onchain
|
||||
|
||||
#### Heir Distribution Errors
|
||||
- ✅ Verify percentages sum to exactly 100%
|
||||
- ✅ For fixed amounts: Ensure total doesn't exceed wallet balance
|
||||
- ✅ Check Bitcoin addresses are valid (use testnet for testing)
|
||||
- ✅ Ensure no duplicate addresses in heir list
|
||||
- ✅ Verify address format: bc1... for native segwit, 1... for legacy
|
||||
|
||||
#### Transaction Creation Fails
|
||||
- ✅ Check wallet has sufficient funds (including fees)
|
||||
- ✅ Verify all heirs have valid, unique addresses
|
||||
- ✅ Ensure locktime format is correct
|
||||
- ✅ Check executor is selected and available
|
||||
- ✅ Verify executor fee is properly configured (fixed amount only)
|
||||
|
||||
#### Executor Fee Issues
|
||||
- ✅ Fee is a fixed BTC amount only (no percentage option)
|
||||
- ✅ Fee is included in transaction output
|
||||
- ✅ Executor receives fee only when transaction confirms
|
||||
- ✅ Transaction must be broadcast and confirmed for executor to get paid
|
||||
|
||||
#### wallet_util/ Not Working
|
||||
- ✅ Copy files to Electrum's plugin directory
|
||||
- ✅ Load Electrum's virtualenv before using
|
||||
- ✅ Run `./bal_wallet_utils_qt.py`
|
||||
- ✅ Only use for emergency wallet fixes
|
||||
- ✅ Backup wallet before using wallet utilities
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Thanks for considering contributing!
|
||||
|
||||
---
|
||||
|
||||
## 📜 License
|
||||
|
||||
MIT License - see [LICENSE](LICENSE) for details.
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Links
|
||||
|
||||
- **Repository**: [https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin](https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin)
|
||||
- **Releases**: [https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/releases](https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/releases)
|
||||
- **Issues**: [https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/issues](https://bitcoin-after.like/bitcoinafterlife/bal-electrum-plugin/issues)
|
||||
- **Discussions**: [https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/discussions](https://bitcoin-after.life/gitea/bitcoinafterlife/bal-electrum-plugin/discussions)
|
||||
|
||||
---
|
||||
|
||||
**⚠️ Important**: Always test with small amounts first. This plugin deals with Bitcoin transactions that may be irreversible.
|
||||
|
||||
**🔒 Security**: Never share your seed phrase or private keys. This plugin only creates transactions, it doesn't store your keys.
|
||||
|
||||
**💡 Note**: The executor fee is a fixed BTC amount included in the transaction output. The executor is financially incentivized to broadcast the transaction and ensure it confirms on the Bitcoin network.
|
||||
|
||||
27
bal.py
27
bal.py
@@ -47,18 +47,19 @@ class BalConfig:
|
||||
|
||||
|
||||
class BalPlugin(BasePlugin):
|
||||
LATEST_VERSION = "1"
|
||||
KNOWN_VERSIONS = ("0", "1")
|
||||
assert LATEST_VERSION in KNOWN_VERSIONS
|
||||
|
||||
def version():
|
||||
try:
|
||||
f = ""
|
||||
with open("VERSION", "r") as fi:
|
||||
f = str(fi.readline())
|
||||
return f
|
||||
except Exception:
|
||||
return "unknown"
|
||||
_version=None
|
||||
__version__ = "0.2.8" #AUTOMATICALLY GENERATED DO NOT EDIT
|
||||
def version(self):
|
||||
if not self._version:
|
||||
try:
|
||||
f = ""
|
||||
with open("{}/VERSION".format(self.plugin_dir), "r") as fi:
|
||||
f = str(fi.read())
|
||||
self._version = f.strip()
|
||||
except Exception as e:
|
||||
_logger.error(f"failed to get version: {e}")
|
||||
self._version="unknown"
|
||||
return self._version
|
||||
|
||||
SIZE = (159, 97)
|
||||
|
||||
@@ -108,7 +109,7 @@ class BalPlugin(BasePlugin):
|
||||
"base_fee": 100000,
|
||||
"status": "New",
|
||||
"info": "Bitcoin After Life Will Executor",
|
||||
"address": "bcrt1qa5cntu4hgadw8zd3n6sq2nzjy34sxdtd9u0gp7",
|
||||
"address": "bc1qusymuetsz2psaqzqxv8qmzcy64d9meckj3lxxf",
|
||||
"selected": True,
|
||||
}
|
||||
},
|
||||
|
||||
62
heirs.py
62
heirs.py
@@ -30,9 +30,11 @@ from electrum.transaction import (
|
||||
PartialTransaction,
|
||||
PartialTxInput,
|
||||
PartialTxOutput,
|
||||
TxOutput,
|
||||
TxOutpoint,
|
||||
# TxOutput,
|
||||
)
|
||||
from electrum.payment_identifier import PaymentIdentifier
|
||||
from electrum.util import (
|
||||
bfh,
|
||||
read_json_file,
|
||||
@@ -44,7 +46,6 @@ from electrum.util import (
|
||||
from .util import Util
|
||||
from .willexecutors import Willexecutors
|
||||
from electrum.util import BitcoinException
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .simple_config import SimpleConfig
|
||||
|
||||
@@ -71,28 +72,22 @@ def reduce_outputs(in_amount, out_amount, fee, outputs):
|
||||
output.value = math.floor((in_amount - fee) / out_amount * output.value)
|
||||
|
||||
|
||||
"""
|
||||
#TODO: put this method inside wallet.db to replace or complete get_locktime_for_new_transaction
|
||||
def get_current_height(network:'Network'):
|
||||
#if no network or not up to date, just set locktime to zero
|
||||
if not network:
|
||||
return 0
|
||||
chain = network.blockchain()
|
||||
if chain.is_tip_stale():
|
||||
return 0
|
||||
# figure out current block height
|
||||
chain_height = chain.height() # learnt from all connected servers, SPV-checked
|
||||
server_height = network.get_server_height() # height claimed by main server, unverified
|
||||
# note: main server might be lagging (either is slow, is malicious, or there is an SPV-invisible-hard-fork)
|
||||
# - if it's lagging too much, it is the network's job to switch away
|
||||
if server_height < chain_height - 10:
|
||||
# the diff is suspiciously large... give up and use something non-fingerprintable
|
||||
return 0
|
||||
# discourage "fee sniping"
|
||||
height = min(chain_height, server_height)
|
||||
return height
|
||||
"""
|
||||
|
||||
def create_op_return_script(data_hex: str) -> bytes:
|
||||
"""Crea scriptpubkey OP_RETURN in bytes"""
|
||||
data = bytes.fromhex(data_hex)
|
||||
|
||||
if len(data) > 80:
|
||||
raise ValueError("OP_RETURN data too big (max 80 bytes)")
|
||||
|
||||
# Costruzione manuale: OP_RETURN + push data
|
||||
if len(data) <= 75:
|
||||
# Formato più comune: OP_RETURN + 1-byte length + data
|
||||
script = b'\x6a' + bytes([len(data)]) + data
|
||||
else:
|
||||
# Per dati più grandi (fino a 80) si usa OP_PUSHDATA1
|
||||
script = b'\x6a\x4c' + bytes([len(data)]) + data
|
||||
|
||||
return script
|
||||
|
||||
def prepare_transactions(locktimes, available_utxos, fees, wallet):
|
||||
available_utxos = sorted(
|
||||
@@ -167,6 +162,13 @@ def prepare_transactions(locktimes, available_utxos, fees, wallet):
|
||||
outputs.append(change)
|
||||
for i in range(0, 100):
|
||||
random.shuffle(outputs)
|
||||
|
||||
#op_return_text = "Hello Bal!"
|
||||
|
||||
## Convert text to hex
|
||||
#op_return_hex = op_return_text.encode('utf-8').hex()
|
||||
#op_return_script = create_op_return_script(op_return_hex)
|
||||
#outputs.append(PartialTxOutput(value=0, scriptpubkey=op_return_script))
|
||||
tx = PartialTransaction.from_io(
|
||||
used_utxos,
|
||||
outputs,
|
||||
@@ -424,6 +426,8 @@ class Heirs(dict, Logger):
|
||||
def prepare_lists(
|
||||
self, balance, total_fees, wallet, willexecutor=False, from_locktime=0
|
||||
):
|
||||
if balance<total_fees or balance < wallet.dust_threshold():
|
||||
raise BalanceTooLowException(balance,wallet.dust_threshold(),total_fees)
|
||||
willexecutors_amount = 0
|
||||
willexecutors = {}
|
||||
heir_list = {}
|
||||
@@ -461,7 +465,6 @@ class Heirs(dict, Logger):
|
||||
percent_amount,
|
||||
fixed_amount_with_dust,
|
||||
) = self.fixed_percent_lists_amount(from_locktime, wallet.dust_threshold())
|
||||
|
||||
if fixed_amount > newbalance:
|
||||
fixed_amount = self.normalize_perc(
|
||||
fixed_heirs, newbalance, fixed_amount, wallet
|
||||
@@ -471,14 +474,12 @@ class Heirs(dict, Logger):
|
||||
heir_list.update(fixed_heirs)
|
||||
|
||||
newbalance -= fixed_amount
|
||||
|
||||
if newbalance > 0:
|
||||
perc_amount = self.normalize_perc(
|
||||
percent_heirs, newbalance, percent_amount, wallet
|
||||
)
|
||||
newbalance -= perc_amount
|
||||
heir_list.update(percent_heirs)
|
||||
|
||||
if newbalance > 0:
|
||||
newbalance += fixed_amount
|
||||
fixed_amount = self.normalize_perc(
|
||||
@@ -537,7 +538,7 @@ class Heirs(dict, Logger):
|
||||
break
|
||||
elif 0 <= j:
|
||||
url, willexecutor = willexecutorsitems[j]
|
||||
if not Willexecutors.is_selected(willexecutor):
|
||||
if not Willexecutors.is_selected(willexecutor) or willexecutor["base_fee"] < wallet.dust_threshold():
|
||||
continue
|
||||
else:
|
||||
willexecutor["url"] = url
|
||||
@@ -782,3 +783,10 @@ class WillExecutorFeeException(Exception):
|
||||
return "WillExecutorFeeException: {} fee:{}".format(
|
||||
self.willexecutor["url"], self.willexecutor["base_fee"]
|
||||
)
|
||||
class BalanceTooLowException(Exception):
|
||||
def __init__(self,balance, dust_threshold, fees):
|
||||
self.balance=balance
|
||||
self.dust_threshold = dust_threshold
|
||||
self.fees = fees
|
||||
def __str__(self):
|
||||
return f"Balance too low, balance: {self.balance}, dust threshold: {self.dust_threshold}, fees: {self.fees}"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "BAL",
|
||||
"fullname": "Bitcoin After Life",
|
||||
"description": "Provides free and decentralized inheritance support<br> Version: 0.2.5",
|
||||
"description": "Provides free and decentralized inheritance support<br> Version: 0.2.8",
|
||||
"author":"Svatantrya",
|
||||
"available_for": ["qt"],
|
||||
"icon":"icons/bal32x32.png"
|
||||
|
||||
289
qt.py
289
qt.py
@@ -15,13 +15,14 @@ from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from functools import partial
|
||||
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Union
|
||||
|
||||
import traceback
|
||||
try:
|
||||
QT_VERSION = sys._GUI_QT_VERSION
|
||||
except Exception:
|
||||
QT_VERSION = 6
|
||||
|
||||
if QT_VERSION == 5:
|
||||
from PyQt5.QtCore import QThread, QCoreApplication
|
||||
from PyQt5.QtCore import (
|
||||
QDateTime,
|
||||
QModelIndex,
|
||||
@@ -57,6 +58,7 @@ if QT_VERSION == 5:
|
||||
QWidget,
|
||||
)
|
||||
else: # QT6
|
||||
from PyQt6.QtCore import QThread, QCoreApplication
|
||||
from PyQt6.QtCore import (
|
||||
QDateTime,
|
||||
QModelIndex,
|
||||
@@ -495,8 +497,8 @@ class BalWindow(Logger):
|
||||
Util.copy(self.will_settings, self.bal_plugin.default_will_settings())
|
||||
self.logger.debug("not_will_settings {}".format(self.will_settings))
|
||||
self.bal_plugin.validate_will_settings(self.will_settings)
|
||||
self.heir_list.update_will_settings()
|
||||
self.heir_list.update()
|
||||
self.heir_list_widget.update_will_settings()
|
||||
self.heir_list_widget.update()
|
||||
|
||||
def init_wizard(self):
|
||||
wizard_dialog = BalWizardDialog(self)
|
||||
@@ -507,9 +509,9 @@ class BalWindow(Logger):
|
||||
self.willexecutor_dialog.show()
|
||||
|
||||
def create_heirs_tab(self):
|
||||
self.heir_list = HeirList(self, self.window)
|
||||
self.heir_list_widget = HeirListWidget(self, self.window)
|
||||
|
||||
tab = self.window.create_list_tab(self.heir_list)
|
||||
tab = self.window.create_list_tab(self.heir_list_widget)
|
||||
tab.is_shown_cv = shown_cv(False)
|
||||
return tab
|
||||
|
||||
@@ -601,14 +603,6 @@ class BalWindow(Logger):
|
||||
except Exception as e:
|
||||
self.show_error(str(e))
|
||||
|
||||
# def export_inheritance_handler(self,path):
|
||||
# txs = self.build_inheritance_transaction(ignore_duplicate=True, keep_original=False)
|
||||
# with open(path,"w") as f:
|
||||
# for tx in txs:
|
||||
# tx['status']+="."+BalPlugin.STATUS_EXPORTED
|
||||
# f.write(str(tx['tx']))
|
||||
# f.write('\n')
|
||||
|
||||
def set_heir(self, heir):
|
||||
heir = list(heir)
|
||||
if not self.bal_plugin.ENABLE_MULTIVERSE.get():
|
||||
@@ -616,7 +610,7 @@ class BalWindow(Logger):
|
||||
|
||||
h = Heirs.validate_heir(heir[0], heir[1:])
|
||||
self.heirs[heir[0]] = h
|
||||
self.heir_list.update()
|
||||
self.heir_list_widget.update()
|
||||
return True
|
||||
|
||||
def delete_heirs(self, heirs):
|
||||
@@ -627,14 +621,12 @@ class BalWindow(Logger):
|
||||
_logger.debug(f"error deleting heir: {heir} {e}")
|
||||
pass
|
||||
self.heirs.save()
|
||||
self.heir_list.update()
|
||||
self.heir_list_widget.update()
|
||||
return True
|
||||
|
||||
def import_heirs(
|
||||
self,
|
||||
):
|
||||
def import_heirs(self):
|
||||
import_meta_gui(
|
||||
self.window, _("heirs"), self.heirs.import_file, self.heir_list.update
|
||||
self.window, _("heirs"), self.heirs.import_file, self.heir_list_widget.update
|
||||
)
|
||||
|
||||
def export_heirs(self):
|
||||
@@ -748,8 +740,7 @@ class BalWindow(Logger):
|
||||
|
||||
def init_class_variables(self):
|
||||
if not self.heirs:
|
||||
raise NoHeirsException()
|
||||
return
|
||||
raise NoHeirsException(_("Heirs are not defined"))
|
||||
try:
|
||||
self.date_to_check = Util.parse_locktime_string(
|
||||
self.will_settings["threshold"]
|
||||
@@ -757,11 +748,13 @@ class BalWindow(Logger):
|
||||
# found = False
|
||||
self.locktime_blocks = self.bal_plugin.LOCKTIME_BLOCKS.get()
|
||||
self.current_block = Util.get_current_height(self.wallet.network)
|
||||
self.block_to_check = self.current_block + self.locktime_blocks
|
||||
self.block_to_check=0
|
||||
self.no_willexecutor = self.bal_plugin.NO_WILLEXECUTOR.get()
|
||||
self.willexecutors = Willexecutors.get_willexecutors(
|
||||
self.bal_plugin, update=True, bal_window=self, task=False
|
||||
)
|
||||
if self.date_to_check < datetime.now().timestamp():
|
||||
raise CheckAliveException(self.date_to_check)
|
||||
self.init_heirs_to_locktime(self.bal_plugin.ENABLE_MULTIVERSE.get())
|
||||
|
||||
except Exception as e:
|
||||
@@ -776,8 +769,8 @@ class BalWindow(Logger):
|
||||
if not self.heirs:
|
||||
self.logger.warning("not heirs {}".format(self.heirs))
|
||||
return
|
||||
self.init_class_variables()
|
||||
try:
|
||||
self.init_class_variables()
|
||||
Will.check_amounts(
|
||||
self.heirs,
|
||||
self.willexecutors,
|
||||
@@ -788,9 +781,12 @@ class BalWindow(Logger):
|
||||
except AmountException as e:
|
||||
self.show_warning(
|
||||
_(
|
||||
f"In the inheritance process, the entire wallet will always be fully emptied. Your settings require an adjustment of the amounts.\n{e}"
|
||||
f"In the inheritance process, the entire wallet will always be fully emptied. Your settings require an adjustment of the amounts.{e}"
|
||||
)
|
||||
)
|
||||
except CheckAliveException:
|
||||
self.show_error(_("CheckAlive is in the past please update it to a date in the future but less than locktime"))
|
||||
return
|
||||
locktime = Util.parse_locktime_string(self.will_settings["locktime"])
|
||||
if locktime < self.date_to_check:
|
||||
self.show_error(_("locktime is lower than threshold"))
|
||||
@@ -1036,7 +1032,18 @@ class BalWindow(Logger):
|
||||
)
|
||||
|
||||
def on_failure(err):
|
||||
a,b,c = err
|
||||
self.logger.error(f"fail to broadcast transactions:{err}")
|
||||
self.logger.error(f"error: {b}")
|
||||
self.logger.error(f"traceback ")
|
||||
tb = c
|
||||
while tb is not None:
|
||||
frame = tb.tb_frame
|
||||
self.logger.error("file:", frame.f_code.co_filename)
|
||||
self.logger.error("name:", frame.f_code.co_name)
|
||||
self.logger.error("line:", tb.tb_lineno)
|
||||
self.logger.error("lasti:", tb.tb_lasti)
|
||||
tb = tb.tb_next
|
||||
|
||||
task = partial(self.push_transactions_to_willexecutors, force)
|
||||
msg = _("Selecting Will-Executors")
|
||||
@@ -1079,7 +1086,13 @@ class BalWindow(Logger):
|
||||
self.willitems[wid].we["url"], wid, "Waiting"
|
||||
)
|
||||
)
|
||||
self.willitems[wid].check_willexecutor()
|
||||
w = self.willitems[wid]
|
||||
w.set_check_willexecutor(
|
||||
Willexecutors.check_transaction(
|
||||
wid,
|
||||
w.we["url"]
|
||||
)
|
||||
)
|
||||
self.waiting_dialog.update(
|
||||
"checked {} - {} : {}".format(
|
||||
self.willitems[wid].we["url"],
|
||||
@@ -1128,7 +1141,9 @@ class BalWindow(Logger):
|
||||
self.waiting_dialog.update(
|
||||
"checking transaction: {}\n willexecutor: {}".format(wid, w.we["url"])
|
||||
)
|
||||
w.check_willexecutor()
|
||||
|
||||
w.set_check_willexecutor(Willexecutors.check_transaction(wid, w.we["url"]))
|
||||
|
||||
|
||||
if time.time() - start < 3:
|
||||
time.sleep(3 - (time.time() - start))
|
||||
@@ -1189,7 +1204,7 @@ class BalWindow(Logger):
|
||||
def on_success(result):
|
||||
# del self.waiting_dialog
|
||||
try:
|
||||
parent.willexecutor_list.update()
|
||||
parent.will_executor_list_widget.update()
|
||||
except Exception as e:
|
||||
pass
|
||||
try:
|
||||
@@ -1214,10 +1229,20 @@ class BalWindow(Logger):
|
||||
self.dw.show()
|
||||
|
||||
def update_all(self):
|
||||
self.will_list.update_will(self.willitems)
|
||||
self.heirs_tab.update()
|
||||
self.will_tab.update()
|
||||
self.will_list.update()
|
||||
try:
|
||||
Will.add_willtree(self.willitems)
|
||||
all_utxos = self.wallet.get_utxos()
|
||||
utxos_list = Will.utxos_strs(all_utxos)
|
||||
Will.check_invalidated(
|
||||
self.willitems, utxos_list, self.wallet
|
||||
)
|
||||
|
||||
self.will_list.update_will(self.willitems)
|
||||
self.heirs_tab.update()
|
||||
self.will_tab.update()
|
||||
self.will_list.update()
|
||||
except Exception as e:
|
||||
_logger.error(f"error while updating window: {e}")
|
||||
|
||||
|
||||
def add_widget(grid, label, widget, row, help_):
|
||||
@@ -1605,17 +1630,19 @@ class BalWizardDialog(BalDialog):
|
||||
)
|
||||
|
||||
def on_accept(self):
|
||||
self.bal_window.update_all()
|
||||
pass
|
||||
|
||||
def on_reject(self):
|
||||
pass
|
||||
|
||||
def on_close(self):
|
||||
self.bal_window.update_all()
|
||||
pass
|
||||
|
||||
def closeEvent(self, event):
|
||||
self.bal_window.update_all()
|
||||
self.bal_window.heir_list.update_will_settings()
|
||||
|
||||
self.bal_window.heir_list_widget.update_will_settings()
|
||||
pass
|
||||
|
||||
|
||||
@@ -1692,7 +1719,7 @@ class BalWizardHeirsWidget(BalWizardWidget):
|
||||
)
|
||||
|
||||
def get_content(self):
|
||||
self.heirs_list = HeirList(self.bal_window, self)
|
||||
self.heir_list_widget = HeirListWidget(self.bal_window, self)
|
||||
button_add = QPushButton(_("Add"))
|
||||
button_add.clicked.connect(self.add_heir)
|
||||
button_import = QPushButton(_("Import"))
|
||||
@@ -1701,20 +1728,20 @@ class BalWizardHeirsWidget(BalWizardWidget):
|
||||
button_export.clicked.connect(self.export_to_file)
|
||||
widget = QWidget()
|
||||
vbox = QVBoxLayout(widget)
|
||||
vbox.addWidget(self.heirs_list)
|
||||
vbox.addWidget(self.heir_list_widget)
|
||||
vbox.addLayout(Buttons(button_add, button_import, button_export))
|
||||
return widget
|
||||
|
||||
def import_from_file(self):
|
||||
self.bal_window.import_heirs()
|
||||
self.heirs_list.update()
|
||||
self.heir_list_widget.update()
|
||||
|
||||
def export_to_file(self):
|
||||
self.bal_window.export_heirs()
|
||||
|
||||
def add_heir(self):
|
||||
self.bal_window.new_heir_dialog()
|
||||
self.heirs_list.update()
|
||||
self.heir_list_widget.update()
|
||||
|
||||
def validate(self):
|
||||
return True
|
||||
@@ -1785,7 +1812,7 @@ class BalWizardWEDownloadWidget(BalWizardWidget):
|
||||
_logger.debug(f"Failed to download willexecutors list {fail}")
|
||||
pass
|
||||
|
||||
task = partial(Willexecutors.download_list, self.bal_window.bal_plugin,self.bal_window.willexecutors)
|
||||
task = partial(Willexecutors.download_list,self.bal_window.willexecutors)
|
||||
msg = _("Downloading Will-Executors list")
|
||||
self.waiting_dialog = BalWaitingDialog(
|
||||
self.bal_window, msg, task, on_success, on_failure, exe=False
|
||||
@@ -1988,6 +2015,7 @@ class BalWaitingDialog(BalDialog):
|
||||
self.thread.stop()
|
||||
|
||||
def update_message(self, msg):
|
||||
print(msg)
|
||||
self.message_label.setText(msg)
|
||||
|
||||
def update(self, msg):
|
||||
@@ -2046,13 +2074,18 @@ class BalBuildWillDialog(BalDialog):
|
||||
parent = bal_window.window
|
||||
BalDialog.__init__(self, parent, bal_window.bal_plugin, _("Building Will"))
|
||||
self.parent = parent
|
||||
self.updatemessage.connect(self.update)
|
||||
self.updatemessage.connect(self.msg_update)
|
||||
self.bal_window = bal_window
|
||||
self.bal_plugin = bal_window.bal_plugin
|
||||
self.message_label = QLabel(_("Building Will:"))
|
||||
self.vbox = QVBoxLayout(self)
|
||||
self.vbox.addWidget(self.message_label)
|
||||
self.qwidget = QWidget()
|
||||
self.vbox.addWidget(self.qwidget)
|
||||
self.vbox.addWidget(self.message_label,0)
|
||||
self.qwidget = QWidget(self)
|
||||
self.vbox.addWidget(self.qwidget,1)
|
||||
self.labelsbox=QVBoxLayout(self.qwidget)
|
||||
self.setMinimumWidth(600)
|
||||
self.setMinimumHeight(100)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
self.labels = []
|
||||
self.check_row = None
|
||||
self.inval_row = None
|
||||
@@ -2079,13 +2112,26 @@ class BalBuildWillDialog(BalDialog):
|
||||
self.exec()
|
||||
|
||||
def task_phase1(self):
|
||||
txs=None
|
||||
_logger.debug("close plugin phase 1 started")
|
||||
varrow = self.msg_set_status("checking variables")
|
||||
try:
|
||||
self.bal_window.init_class_variables()
|
||||
except NoHeirsException:
|
||||
_logger.error("no heirs exception")
|
||||
return False, None
|
||||
varrow = self.msg_set_status("checking variables")
|
||||
except CheckAliveException as cae:
|
||||
fee_per_byte = self.bal_window.will_settings.get("baltx_fees", 1)
|
||||
tx = Will.invalidate_will(
|
||||
self.bal_window.willitems, self.bal_window.wallet, fee_per_byte
|
||||
)
|
||||
if tx:
|
||||
_logger.debug("during phase1 CAE: {}, Continue to invalidate".format(cae))
|
||||
self.msg_set_checking(self.msg_warning("Check Alive Threshold Passed: you have to Invalidate your old Will"))
|
||||
else:
|
||||
raise cae
|
||||
return None, tx
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise e
|
||||
try:
|
||||
_logger.debug("checking variables")
|
||||
Will.check_amounts(
|
||||
@@ -2121,9 +2167,10 @@ class BalBuildWillDialog(BalDialog):
|
||||
return None, Will.invalidate_will(
|
||||
self.bal_window.willitems, self.bal_window.wallet, fee_per_byte
|
||||
)
|
||||
except NoHeirsException:
|
||||
except NoHeirsException as e:
|
||||
_logger.debug("no heirs")
|
||||
self.msg_set_checking("No Heirs")
|
||||
raise e
|
||||
except NotCompleteWillException as e:
|
||||
_logger.debug(f"not complete {e} true")
|
||||
message = False
|
||||
@@ -2147,13 +2194,15 @@ class BalBuildWillDialog(BalDialog):
|
||||
if have_to_build:
|
||||
self.msg_set_building()
|
||||
try:
|
||||
if not self.bal_window.build_will():
|
||||
txs = self.bal_window.build_will()
|
||||
if not txs:
|
||||
self.msg_set_status(
|
||||
_("Balance is too low. No transaction was built"),
|
||||
None,
|
||||
_("Skipped"),
|
||||
self.COLOR_ERROR,
|
||||
)
|
||||
return False,None
|
||||
|
||||
self.bal_window.check_will()
|
||||
for wid in Will.only_valid(self.bal_window.willitems):
|
||||
@@ -2185,12 +2234,14 @@ class BalBuildWillDialog(BalDialog):
|
||||
if not self.bal_window.willitems[wid].get_status("COMPLETE"):
|
||||
have_to_sign = True
|
||||
break
|
||||
return have_to_sign, None
|
||||
return have_to_sign, txs
|
||||
|
||||
def on_accept(self):
|
||||
self.bal_window.update_all()
|
||||
pass
|
||||
|
||||
def on_accept_phase2(self):
|
||||
self.bal_window.update_all()
|
||||
pass
|
||||
|
||||
def on_error_push(self):
|
||||
@@ -2228,6 +2279,7 @@ class BalBuildWillDialog(BalDialog):
|
||||
self.msg_set_pushing(_("Broadcasting"))
|
||||
retry = False
|
||||
try:
|
||||
|
||||
willexecutors = Willexecutors.get_willexecutor_transactions(
|
||||
self.bal_window.willitems
|
||||
)
|
||||
@@ -2257,7 +2309,10 @@ class BalBuildWillDialog(BalDialog):
|
||||
self.bal_window.willitems[wid].we["url"], wid, "Waiting"
|
||||
)
|
||||
)
|
||||
self.bal_window.willitems[wid].check_willexecutor()
|
||||
self.bal_plugin = self.bal_window.bal_plugin
|
||||
w = self.bal_window.willitems[wid]
|
||||
|
||||
w.set_check_willexecutor(Willexecutors.check_transaction(wid, w.we["url"]))
|
||||
row = self.msg_edit_row(
|
||||
"checked {} - {} : {}".format(
|
||||
self.bal_window.willitems[wid].we["url"],
|
||||
@@ -2268,7 +2323,6 @@ class BalBuildWillDialog(BalDialog):
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
|
||||
_logger.error(f"loop push error:{e}")
|
||||
raise e
|
||||
if retry:
|
||||
@@ -2306,12 +2360,11 @@ class BalBuildWillDialog(BalDialog):
|
||||
on_error=self.on_error_phase1,
|
||||
)
|
||||
|
||||
def on_error(self, error):
|
||||
_logger.error(error)
|
||||
pass
|
||||
|
||||
def on_success_phase1(self, result):
|
||||
self.have_to_sign, tx = list(result)
|
||||
#if not tx:
|
||||
# self.msg_edit_row(self.msg_error("Error, no tx was built"))
|
||||
# return
|
||||
_logger.debug("have to sign {}".format(self.have_to_sign))
|
||||
password = None
|
||||
if self.have_to_sign is None:
|
||||
@@ -2359,7 +2412,6 @@ class BalBuildWillDialog(BalDialog):
|
||||
self.close()
|
||||
|
||||
def closeEvent(self, event):
|
||||
self.bal_window.update_all()
|
||||
self._stopping = True
|
||||
self.thread.stop()
|
||||
|
||||
@@ -2388,15 +2440,26 @@ class BalBuildWillDialog(BalDialog):
|
||||
self.msg_set_pushing(self.msg_ok())
|
||||
|
||||
except Exception as e:
|
||||
td = traceback.format_exc()
|
||||
self.msg_set_pushing(self.msg_error(e))
|
||||
self.msg_edit_row(self.msg_ok())
|
||||
self.wait(5)
|
||||
|
||||
def on_error(self, error):
|
||||
_logger.error(error)
|
||||
pass
|
||||
|
||||
def on_error_phase1(self, error):
|
||||
_logger.error(f"error phase1: {error}")
|
||||
self.bal_window.update_all()
|
||||
a,b,c = error
|
||||
self.msg_edit_row(self.msg_error(f"Error: {b}"))
|
||||
_logger.error(f"error phase1: {b}")
|
||||
|
||||
def on_error_phase2(self, error):
|
||||
_logger.error(f"error phase2: { error}")
|
||||
self.bal_window.upade_all()
|
||||
a,b,c = error
|
||||
self.msg_edit_row(self.msg_error(f"Error: {b}"))
|
||||
_logger.error(f"error phase2: {b}")
|
||||
|
||||
def msg_set_checking(self, status="Waiting", row=None):
|
||||
row = self.check_row if row is None else row
|
||||
@@ -2448,10 +2511,11 @@ class BalBuildWillDialog(BalDialog):
|
||||
def msg_edit_row(self, line, row=None):
|
||||
try:
|
||||
self.labels[row] = line
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
self.labels.append(line)
|
||||
row = len(self.labels) - 1
|
||||
|
||||
|
||||
self.updatemessage.emit()
|
||||
|
||||
return row
|
||||
@@ -2463,13 +2527,36 @@ class BalBuildWillDialog(BalDialog):
|
||||
pass
|
||||
self.updatemessage.emit()
|
||||
|
||||
def update(self):
|
||||
self.vbox.removeWidget(self.qwidget)
|
||||
self.qwidget = QWidget(self)
|
||||
labelsbox = QVBoxLayout(self.qwidget)
|
||||
for label in self.labels:
|
||||
labelsbox.addWidget(QLabel(label))
|
||||
self.vbox.addWidget(self.qwidget)
|
||||
def clear_layout(self,layout):
|
||||
while layout.count():
|
||||
item = layout.takeAt(0)
|
||||
w = item.widget()
|
||||
if w:
|
||||
w.setParent(None)
|
||||
w.deleteLater()
|
||||
|
||||
#def msg_update(self):
|
||||
# self.clear_layout(self.labelsbox)
|
||||
# for label in self.labels:
|
||||
# label=label.replace("\n","<br>")
|
||||
# qlabel=QLabel(label)
|
||||
# qlabel.setWordWrap(True)
|
||||
# self.labelsbox.addWidget(qlabel)
|
||||
|
||||
# self.labelsbox.activate()
|
||||
# self.qwidget.setMinimumSize(self.labelsbox.sizeHint())
|
||||
# self.qwidget.adjustSize()
|
||||
# from PyQt6.QtWidgets import QApplication
|
||||
# QApplication.processEvents()
|
||||
#
|
||||
# self.adjustSize()
|
||||
def msg_update(self):
|
||||
full_text = "<br><br>".join(self.labels).replace("\n", "<br>")
|
||||
self.message_label.setText(full_text)
|
||||
self.message_label.adjustSize()
|
||||
#self.setMinimumHeight(len(self.labels)*40)
|
||||
self.resize(self.sizeHint())
|
||||
|
||||
|
||||
def get_text(self):
|
||||
return self.message_label.text()
|
||||
@@ -2477,7 +2564,7 @@ class BalBuildWillDialog(BalDialog):
|
||||
pass
|
||||
|
||||
|
||||
class HeirList(MyTreeView, MessageBoxMixin):
|
||||
class HeirListWidget(MyTreeView, MessageBoxMixin):
|
||||
class Columns(MyTreeView.BaseColumnsEnum):
|
||||
NAME = enum.auto()
|
||||
ADDRESS = enum.auto()
|
||||
@@ -2492,9 +2579,16 @@ class HeirList(MyTreeView, MessageBoxMixin):
|
||||
|
||||
ROLE_SORT_ORDER = Qt.ItemDataRole.UserRole + 1000
|
||||
|
||||
ROLE_HEIR_KEY = Qt.ItemDataRole.UserRole + 1001
|
||||
ROLE_HEIR_KEY = Qt.ItemDataRole.UserRole + 4000
|
||||
key_role = ROLE_HEIR_KEY
|
||||
|
||||
def createEditor(self, parent, option, index):
|
||||
return QLineEdit(parent)
|
||||
def setEditorData(self, editor, index):
|
||||
editor.setText(index.data())
|
||||
def setModelData(self, editor, model, index):
|
||||
model.setData(index, editor.text())
|
||||
|
||||
def __init__(self, bal_window: "BalWindow", parent):
|
||||
super().__init__(
|
||||
parent=parent,
|
||||
@@ -2509,6 +2603,7 @@ class HeirList(MyTreeView, MessageBoxMixin):
|
||||
self.decimal_point = bal_window.window.get_decimal_point()
|
||||
self.bal_window = bal_window
|
||||
|
||||
|
||||
try:
|
||||
self.setModel(QStandardItemModel(self))
|
||||
self.sortByColumn(self.Columns.NAME, Qt.SortOrder.AscendingOrder)
|
||||
@@ -2592,12 +2687,6 @@ class HeirList(MyTreeView, MessageBoxMixin):
|
||||
menu.addAction(_("Delete"), lambda: self.delete_heirs(selected_keys))
|
||||
menu.exec(self.viewport().mapToGlobal(position))
|
||||
|
||||
# def get_selected_keys(self):
|
||||
# selected_keys = []
|
||||
# for s_idx in self.selected_in_column(self.Columns.NAME):
|
||||
# sel_key = self.model().itemFromIndex(s_idx).data(0)
|
||||
# selected_keys.append(sel_key)
|
||||
# return selected_keys
|
||||
def update(self):
|
||||
current_key = self.get_role_data_for_current_item(
|
||||
col=self.Columns.NAME, role=self.ROLE_HEIR_KEY
|
||||
@@ -2747,6 +2836,7 @@ class HeirList(MyTreeView, MessageBoxMixin):
|
||||
self.heir_tx_fees.setValue(int(self.bal_window.will_settings["baltx_fees"]))
|
||||
|
||||
except Exception as e:
|
||||
pass
|
||||
_logger.debug(f"Exception update_will_settings {e}")
|
||||
|
||||
def build_transactions(self):
|
||||
@@ -2965,16 +3055,16 @@ class PreviewList(MyTreeView):
|
||||
|
||||
wizard = QPushButton(_("Setup Wizard"))
|
||||
wizard.clicked.connect(self.bal_window.init_wizard)
|
||||
display = QPushButton(_("Display"))
|
||||
display.clicked.connect(self.bal_window.preview_modal_dialog)
|
||||
#display = QPushButton(_("Display"))
|
||||
#display.clicked.connect(self.bal_window.preview_modal_dialog)
|
||||
|
||||
display = QPushButton(_("Refresh"))
|
||||
display.clicked.connect(self.check)
|
||||
refresh = QPushButton(_("Refresh"))
|
||||
refresh.clicked.connect(self.check)
|
||||
|
||||
widget = QWidget()
|
||||
hlayout = QHBoxLayout(widget)
|
||||
hlayout.addWidget(wizard)
|
||||
hlayout.addWidget(display)
|
||||
hlayout.addWidget(refresh)
|
||||
toolbar.insertWidget(2, widget)
|
||||
|
||||
self.menu = menu
|
||||
@@ -3012,13 +3102,6 @@ class PreviewList(MyTreeView):
|
||||
self.update()
|
||||
|
||||
def check(self):
|
||||
Will.add_willtree(self.bal_window.willitems)
|
||||
all_utxos = self.bal_window.wallet.get_utxos()
|
||||
utxos_list = Will.utxos_strs(all_utxos)
|
||||
Will.check_invalidated(
|
||||
self.bal_window.willitems, utxos_list, self.bal_window.wallet
|
||||
)
|
||||
|
||||
close_window = BalBuildWillDialog(self.bal_window)
|
||||
close_window.build_will_task()
|
||||
|
||||
@@ -3065,7 +3148,10 @@ class PreviewDialog(BalDialog, MessageBoxMixin):
|
||||
self.size_label = QLabel()
|
||||
self.transactions_list = PreviewList(self.bal_window, self.will)
|
||||
|
||||
self.bal_window.init_class_variables()
|
||||
try:
|
||||
self.bal_window.init_class_variables()
|
||||
except Exception as e:
|
||||
_logger.error(f"PreviewDialog Exception: {e}")
|
||||
self.check_will()
|
||||
|
||||
vbox = QVBoxLayout(self)
|
||||
@@ -3311,7 +3397,7 @@ class WillWidget(QWidget):
|
||||
hlayout.addWidget(WillWidget(w, parent=parent))
|
||||
|
||||
|
||||
class WillExecutorList(MyTreeView):
|
||||
class WillExecutorListWidget(MyTreeView):
|
||||
class Columns(MyTreeView.BaseColumnsEnum):
|
||||
SELECTED = enum.auto()
|
||||
URL = enum.auto()
|
||||
@@ -3556,7 +3642,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
|
||||
self.willexecutors_list = Willexecutors.get_willexecutors(self.bal_plugin)
|
||||
|
||||
self.size_label = QLabel()
|
||||
self.willexecutor_list = WillExecutorList(self)
|
||||
self.will_executor_list_widget = WillExecutorListWidget(self)
|
||||
|
||||
vbox = QVBoxLayout(self)
|
||||
vbox.addWidget(self.size_label)
|
||||
@@ -3573,7 +3659,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
|
||||
hbox.addWidget(spacer_widget)
|
||||
vbox.addWidget(widget)
|
||||
|
||||
vbox.addWidget(self.willexecutor_list)
|
||||
vbox.addWidget(self.will_executor_list_widget)
|
||||
buttonbox = QHBoxLayout()
|
||||
|
||||
b = QPushButton(_("Add"))
|
||||
@@ -3597,7 +3683,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
|
||||
buttonbox.addWidget(b)
|
||||
|
||||
vbox.addLayout(buttonbox)
|
||||
# self.willexecutor_list.update()
|
||||
# self.will_executor_list_widget.update()
|
||||
|
||||
def add(self):
|
||||
self.willexecutors_list["http://localhost:8080"] = {
|
||||
@@ -3605,11 +3691,11 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
|
||||
"base_fee": 0,
|
||||
"status": "-1",
|
||||
}
|
||||
self.willexecutor_list.update()
|
||||
self.will_executor_list_widget.update()
|
||||
|
||||
def download_list(self):
|
||||
self.willexecutors_list.update(Willexecutors.download_list(self.bal_plugin,self.bal_window.willexecutors))
|
||||
self.willexecutor_list.update()
|
||||
self.willexecutors_list.update(Willexecutors.download_list(self.bal_window.willexecutors))
|
||||
self.will_executor_list_widget.update()
|
||||
|
||||
def export_file(self, path):
|
||||
Util.export_meta_gui(
|
||||
@@ -3632,13 +3718,13 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
|
||||
wes = self.willexecutors_list
|
||||
self.bal_window.ping_willexecutors(wes, self.parent)
|
||||
self.willexecutors_list.update(wes)
|
||||
self.willexecutor_list.update()
|
||||
self.will_executor_list_widget.update()
|
||||
|
||||
def import_json_file(self, path):
|
||||
data = read_json_file(path)
|
||||
data = self._validate(data)
|
||||
self.willexecutors_list.update(data)
|
||||
self.willexecutor_list.update()
|
||||
self.will_executor_list_widget.update()
|
||||
|
||||
# TODO validate willexecutor json import file
|
||||
def _validate(self, data):
|
||||
@@ -3662,10 +3748,10 @@ class WillExecutorDialog(BalDialog, MessageBoxMixin):
|
||||
self.setMinimumSize(1000, 200)
|
||||
|
||||
vbox = QVBoxLayout(self)
|
||||
self.willexecutor_list = WillExecutorWidget(
|
||||
self.will_executor_list_widget = WillExecutorWidget(
|
||||
self, self.bal_window, self.willexecutors_list
|
||||
)
|
||||
vbox.addWidget(self.willexecutor_list)
|
||||
vbox.addWidget(self.will_executor_list_widget)
|
||||
|
||||
def is_hidden(self):
|
||||
return self.isMinimized() or self.isHidden()
|
||||
@@ -3682,3 +3768,10 @@ class WillExecutorDialog(BalDialog, MessageBoxMixin):
|
||||
|
||||
def closeEvent(self, event):
|
||||
event.accept()
|
||||
|
||||
|
||||
class CheckAliveException(Exception):
|
||||
def __init__(self,timestamp_to_check):
|
||||
self.timestamp_to_check = timestamp_to_check
|
||||
def __str__(self):
|
||||
return "Check alive expired please update it: {}".format(datetime.fromtimestamp(self.timestamp_to_check).isoformat())
|
||||
|
||||
555
util.py
555
util.py
@@ -1,3 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Utility module for the BAL Electrum plugin.
|
||||
|
||||
import bisect
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
@@ -10,7 +14,26 @@ LOCKTIME_THRESHOLD = 500000000
|
||||
|
||||
|
||||
class Util:
|
||||
"""Utility class providing static methods for the BAL Electrum Plugin.
|
||||
|
||||
Contains helper functions for locktime handling, amount encoding/decoding,
|
||||
heir and will-executor comparison, UTXO and transaction comparison,
|
||||
debug printing, and data migration helpers.
|
||||
"""
|
||||
def locktime_to_str(locktime):
|
||||
"""Convert a locktime value to a human-readable string.
|
||||
|
||||
If the locktime is a Unix timestamp (greater than LOCKTIME_THRESHOLD),
|
||||
it is converted to an ISO 8601 date string. Otherwise, it is returned
|
||||
as a plain string (typically a block height).
|
||||
|
||||
Args:
|
||||
locktime: A locktime value, either a block height or a Unix timestamp.
|
||||
|
||||
Returns:
|
||||
str: An ISO 8601 date string for timestamps, or the numeric value
|
||||
as a string for block heights.
|
||||
"""
|
||||
try:
|
||||
locktime = int(locktime)
|
||||
if locktime > LOCKTIME_THRESHOLD:
|
||||
@@ -22,6 +45,20 @@ class Util:
|
||||
return str(locktime)
|
||||
|
||||
def str_to_locktime(locktime):
|
||||
"""Convert a string representation to a locktime value.
|
||||
|
||||
If the string ends with a suffix ('y', 'd', 'b'), it is preserved as-is
|
||||
for later parsing. Numeric strings are converted to integers. ISO 8601
|
||||
date strings are converted to Unix timestamps.
|
||||
|
||||
Args:
|
||||
locktime (str): A locktime string, number, ISO date, or
|
||||
suffixed interval ('y' for years, 'd' for days, 'b' for blocks).
|
||||
|
||||
Returns:
|
||||
int or str: An integer locktime value, or the original string if it
|
||||
carries a suffix for deferred parsing.
|
||||
"""
|
||||
try:
|
||||
if locktime[-1] in ("y", "d", "b"):
|
||||
return locktime
|
||||
@@ -34,6 +71,23 @@ class Util:
|
||||
return int(timestamp)
|
||||
|
||||
def parse_locktime_string(locktime, w=None):
|
||||
"""Parse a locktime string into an integer locktime value.
|
||||
|
||||
Supports multiple formats:
|
||||
- Plain integer: returned directly.
|
||||
- Suffix 'y': converted to days (N * 365) then to a timestamp at midnight.
|
||||
- Suffix 'd': converted to a timestamp N days from now at midnight.
|
||||
- Suffix 'b': added to the current block height (requires wallet network).
|
||||
|
||||
Args:
|
||||
locktime (str): The locktime string to parse.
|
||||
w (optional): The Electrum wallet, used to resolve block-height-based
|
||||
locktimes. Defaults to None.
|
||||
|
||||
Returns:
|
||||
int: The resolved locktime as an integer (timestamp or block height),
|
||||
or 0 if parsing fails.
|
||||
"""
|
||||
try:
|
||||
return int(locktime)
|
||||
|
||||
@@ -61,6 +115,21 @@ class Util:
|
||||
return 0
|
||||
|
||||
def int_locktime(seconds=0, minutes=0, hours=0, days=0, blocks=0):
|
||||
"""Convert time intervals into a locktime integer value in seconds.
|
||||
|
||||
Each unit is converted to seconds and summed. Block intervals are
|
||||
estimated at 600 seconds (10 minutes) per block.
|
||||
|
||||
Args:
|
||||
seconds (int): Number of seconds. Defaults to 0.
|
||||
minutes (int): Number of minutes. Defaults to 0.
|
||||
hours (int): Number of hours. Defaults to 0.
|
||||
days (int): Number of days. Defaults to 0.
|
||||
blocks (int): Number of blocks (600 seconds each). Defaults to 0.
|
||||
|
||||
Returns:
|
||||
int: Total time in seconds.
|
||||
"""
|
||||
return int(
|
||||
seconds
|
||||
+ minutes * 60
|
||||
@@ -70,6 +139,20 @@ class Util:
|
||||
)
|
||||
|
||||
def encode_amount(amount, decimal_point):
|
||||
"""Encode a human-readable amount string to an integer value.
|
||||
|
||||
If the amount is a percentage (ends with '%'), it is returned as-is.
|
||||
Otherwise, the float value is multiplied by 10^decimal_point to convert
|
||||
to the smallest unit (e.g., satoshis for BTC).
|
||||
|
||||
Args:
|
||||
amount (str): The amount string, either a number or a percentage.
|
||||
decimal_point (int): The number of decimal places for encoding.
|
||||
|
||||
Returns:
|
||||
str or int: The encoded integer amount, the original percentage string,
|
||||
or 0 if encoding fails.
|
||||
"""
|
||||
if Util.is_perc(amount):
|
||||
return amount
|
||||
else:
|
||||
@@ -79,6 +162,20 @@ class Util:
|
||||
return 0
|
||||
|
||||
def decode_amount(amount, decimal_point):
|
||||
"""Decode an integer amount to a human-readable string.
|
||||
|
||||
If the amount is a percentage (ends with '%'), it is returned as-is.
|
||||
Otherwise, the integer value is divided by 10^decimal_point and formatted
|
||||
to the specified number of decimal places.
|
||||
|
||||
Args:
|
||||
amount: The amount to decode, either an integer or a percentage string.
|
||||
decimal_point (int): The number of decimal places for formatting.
|
||||
|
||||
Returns:
|
||||
str: The decoded amount string formatted to decimal_point places,
|
||||
the original percentage string, or a string representation on error.
|
||||
"""
|
||||
if Util.is_perc(amount):
|
||||
return amount
|
||||
else:
|
||||
@@ -89,12 +186,30 @@ class Util:
|
||||
return str(amount)
|
||||
|
||||
def is_perc(value):
|
||||
"""Check whether a value represents a percentage.
|
||||
|
||||
Args:
|
||||
value: The value to check.
|
||||
|
||||
Returns:
|
||||
bool: True if the value ends with '%', False otherwise or on error.
|
||||
"""
|
||||
try:
|
||||
return value[-1] == "%"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def cmp_array(heira, heirb):
|
||||
"""Compare two heir arrays element by element.
|
||||
|
||||
Args:
|
||||
heira (list): First heir array.
|
||||
heirb (list): Second heir array.
|
||||
|
||||
Returns:
|
||||
bool: True if both arrays have the same length and identical elements,
|
||||
False otherwise.
|
||||
"""
|
||||
try:
|
||||
if len(heira) != len(heirb):
|
||||
return False
|
||||
@@ -106,11 +221,32 @@ class Util:
|
||||
return False
|
||||
|
||||
def cmp_heir(heira, heirb):
|
||||
"""Compare two heirs by their address and amount.
|
||||
|
||||
Args:
|
||||
heira: First heir (index 0=address, index 1=amount).
|
||||
heirb: Second heir (same format).
|
||||
|
||||
Returns:
|
||||
bool: True if both heirs have the same address and amount.
|
||||
"""
|
||||
if heira[0] == heirb[0] and heira[1] == heirb[1]:
|
||||
return True
|
||||
return False
|
||||
|
||||
def cmp_willexecutor(willexecutora, willexecutorb):
|
||||
"""Compare two will executors for equality.
|
||||
|
||||
Two executors are considered equal if they are the same object, or if they
|
||||
share the same url, address, and base_fee.
|
||||
|
||||
Args:
|
||||
willexecutora (dict): First will executor dictionary.
|
||||
willexecutorb (dict): Second will executor dictionary.
|
||||
|
||||
Returns:
|
||||
bool: True if the executors are equal, False otherwise.
|
||||
"""
|
||||
if willexecutora == willexecutorb:
|
||||
return True
|
||||
try:
|
||||
@@ -125,6 +261,19 @@ class Util:
|
||||
return False
|
||||
|
||||
def search_heir_by_values(heirs, heir, values):
|
||||
"""Search for an heir in a dict by matching specific field values.
|
||||
|
||||
Iterates over all heirs and returns the key of the first heir whose
|
||||
values for all specified fields match those of the given heir.
|
||||
|
||||
Args:
|
||||
heirs (dict): Dictionary of heirs keyed by ID.
|
||||
heir (dict): The reference heir to match against.
|
||||
values (list): List of field keys to compare.
|
||||
|
||||
Returns:
|
||||
str or bool: The key of the first matching heir, or False if no match.
|
||||
"""
|
||||
for h, v in heirs.items():
|
||||
found = False
|
||||
for val in values:
|
||||
@@ -136,6 +285,16 @@ class Util:
|
||||
return False
|
||||
|
||||
def cmp_heir_by_values(heira, heirb, values):
|
||||
"""Compare two heirs by a set of specific field values.
|
||||
|
||||
Args:
|
||||
heira (dict): First heir data dictionary.
|
||||
heirb (dict): Second heir data dictionary.
|
||||
values (list): List of field keys to compare.
|
||||
|
||||
Returns:
|
||||
bool: True if all specified fields match between both heirs.
|
||||
"""
|
||||
for v in values:
|
||||
if heira[v] != heirb[v]:
|
||||
return False
|
||||
@@ -144,6 +303,24 @@ class Util:
|
||||
def cmp_heirs_by_values(
|
||||
heirsa, heirsb, values, exclude_willexecutors=False, reverse=True
|
||||
):
|
||||
"""Compare two heir dictionaries by specific field values.
|
||||
|
||||
Performs a bidirectional comparison: every heir in heirsa must have a
|
||||
matching heir in heirsb (and vice versa when reverse=True) for the
|
||||
specified field values.
|
||||
|
||||
Args:
|
||||
heirsa (dict): First dictionary of heirs.
|
||||
heirsb (dict): Second dictionary of heirs.
|
||||
values (list): Field keys to compare.
|
||||
exclude_willexecutors (bool): If True, exclude will-executor entries
|
||||
(containing 'w!ll3x3c"') from comparison. Defaults to False.
|
||||
reverse (bool): If True, also verify the reverse comparison. Defaults
|
||||
to True.
|
||||
|
||||
Returns:
|
||||
bool: True if all matching heirs are found in both directions.
|
||||
"""
|
||||
for heira in heirsa:
|
||||
if (
|
||||
exclude_willexecutors and 'w!ll3x3c"' not in heira
|
||||
@@ -171,6 +348,26 @@ class Util:
|
||||
cmp_function=lambda x, y: x[0] == y[0] and x[3] == y[3],
|
||||
reverse=True,
|
||||
):
|
||||
"""Compare two heir dictionaries using a custom comparison function.
|
||||
|
||||
Performs a bidirectional comparison. Will-executor entries are excluded
|
||||
from the comparison. If an exact key match fails, a fallback search by
|
||||
values (indices 0 and 3) is attempted.
|
||||
|
||||
Args:
|
||||
heirsa (dict): First dictionary of heirs.
|
||||
heirsb (dict): Second dictionary of heirs.
|
||||
cmp_function (callable): A function taking two heir values and returning
|
||||
a bool. Defaults to comparing index 0 (address) and index 3.
|
||||
reverse (bool): If True, also verify the reverse comparison. Defaults
|
||||
to True.
|
||||
|
||||
Returns:
|
||||
bool: True if all heirs match in both directions.
|
||||
|
||||
Raises:
|
||||
Exception: Re-raises any exception encountered during comparison.
|
||||
"""
|
||||
try:
|
||||
for heir in heirsa:
|
||||
if 'w!ll3x3c"' not in heir:
|
||||
@@ -188,6 +385,16 @@ class Util:
|
||||
return False
|
||||
|
||||
def cmp_inputs(inputsa, inputsb):
|
||||
"""Compare two lists of transaction inputs for equality.
|
||||
|
||||
Args:
|
||||
inputsa (list): First list of transaction inputs.
|
||||
inputsb (list): Second list of transaction inputs.
|
||||
|
||||
Returns:
|
||||
bool: True if both lists have the same length and every input in
|
||||
inputsa is found in inputsb.
|
||||
"""
|
||||
if len(inputsa) != len(inputsb):
|
||||
return False
|
||||
for inputa in inputsa:
|
||||
@@ -196,6 +403,21 @@ class Util:
|
||||
return True
|
||||
|
||||
def cmp_outputs(outputsa, outputsb, willexecutor_output=None):
|
||||
"""Compare two lists of transaction outputs for equality.
|
||||
|
||||
Optionally excludes a specific will-executor output from the comparison,
|
||||
as it may differ between transactions.
|
||||
|
||||
Args:
|
||||
outputsa (list): First list of transaction outputs.
|
||||
outputsb (list): Second list of transaction outputs.
|
||||
willexecutor_output: An output to exclude from comparison. Defaults
|
||||
to None.
|
||||
|
||||
Returns:
|
||||
bool: True if both lists have the same length and all outputs match,
|
||||
excluding the willexecutor_output if provided.
|
||||
"""
|
||||
if len(outputsa) != len(outputsb):
|
||||
return False
|
||||
for outputa in outputsa:
|
||||
@@ -205,6 +427,15 @@ class Util:
|
||||
return True
|
||||
|
||||
def cmp_txs(txa, txb):
|
||||
"""Compare two transactions for equality by inputs and outputs.
|
||||
|
||||
Args:
|
||||
txa: First transaction object.
|
||||
txb: Second transaction object.
|
||||
|
||||
Returns:
|
||||
bool: True if both transactions have matching inputs and outputs.
|
||||
"""
|
||||
if not Util.cmp_inputs(txa.inputs(), txb.inputs()):
|
||||
return False
|
||||
if not Util.cmp_outputs(txa.outputs(), txb.outputs()):
|
||||
@@ -212,6 +443,20 @@ class Util:
|
||||
return True
|
||||
|
||||
def get_value_amount(txa, txb):
|
||||
"""Calculate the total value of outputs that appear in both transactions.
|
||||
|
||||
For each output in txa, checks if a matching output (same amount and/or
|
||||
same address) exists in txb. Returns the sum of matched output values,
|
||||
or False if any output has neither a matching amount nor address.
|
||||
|
||||
Args:
|
||||
txa: Reference transaction (whose outputs are evaluated).
|
||||
txb: Comparison transaction.
|
||||
|
||||
Returns:
|
||||
int or False: Total satoshi value of matched outputs, or False if
|
||||
any output has no correspondence at all.
|
||||
"""
|
||||
outputsa = txa.outputs()
|
||||
# outputsb = txb.outputs()
|
||||
value_amount = 0
|
||||
@@ -230,6 +475,24 @@ class Util:
|
||||
return value_amount
|
||||
|
||||
def chk_locktime(timestamp_to_check, block_height_to_check, locktime):
|
||||
"""Check whether a locktime has been reached.
|
||||
|
||||
If the locktime is a Unix timestamp (above LOCKTIME_THRESHOLD), it is
|
||||
compared against timestamp_to_check. If it is a block height (below the
|
||||
threshold), it is compared against block_height_to_check.
|
||||
|
||||
Note:
|
||||
There is a known issue at the threshold boundary (LOCKTIME_THRESHOLD)
|
||||
where the behavior is ambiguous.
|
||||
|
||||
Args:
|
||||
timestamp_to_check (int): Current Unix timestamp to compare against.
|
||||
block_height_to_check (int): Current block height to compare against.
|
||||
locktime (int): The locktime value to check.
|
||||
|
||||
Returns:
|
||||
bool: True if the locktime has been reached or exceeded.
|
||||
"""
|
||||
# TODO BUG: WHAT HAPPEN AT THRESHOLD?
|
||||
locktime = int(locktime)
|
||||
if locktime > LOCKTIME_THRESHOLD and locktime > timestamp_to_check:
|
||||
@@ -240,6 +503,25 @@ class Util:
|
||||
return False
|
||||
|
||||
def anticipate_locktime(locktime, blocks=0, hours=0, days=0):
|
||||
"""Anticipate a locktime by subtracting a time interval from it.
|
||||
|
||||
Used to compute the checkalive time: the point at which the plugin
|
||||
should verify whether the user is still alive before the locktime expires.
|
||||
|
||||
For timestamp-based locktimes, the interval is subtracted as seconds.
|
||||
For block-height-based locktimes, the interval is converted to block
|
||||
equivalents (hours * 6 + days * 144) and subtracted.
|
||||
|
||||
Args:
|
||||
locktime (int): The original locktime value (timestamp or block height).
|
||||
blocks (int): Number of blocks to subtract (each ~10 min). Defaults to 0.
|
||||
hours (int): Number of hours to subtract. Defaults to 0.
|
||||
days (int): Number of days to subtract. Defaults to 0.
|
||||
|
||||
Returns:
|
||||
int: The anticipated locktime, adjusted by the specified interval.
|
||||
Returns at least 1 to avoid invalid values.
|
||||
"""
|
||||
locktime = int(locktime)
|
||||
out = 0
|
||||
if locktime > LOCKTIME_THRESHOLD:
|
||||
@@ -256,6 +538,18 @@ class Util:
|
||||
return out
|
||||
|
||||
def cmp_locktime(locktimea, locktimeb):
|
||||
"""Compare two locktime values.
|
||||
|
||||
If the locktimes are equal, returns 0. If both are suffixed strings
|
||||
with the same unit suffix, compares their numeric parts.
|
||||
|
||||
Args:
|
||||
locktimea: First locktime value.
|
||||
locktimeb: Second locktime value.
|
||||
|
||||
Returns:
|
||||
int: Negative if locktimea < locktimeb, 0 if equal, positive if greater.
|
||||
"""
|
||||
if locktimea == locktimeb:
|
||||
return 0
|
||||
strlocktimea = str(locktimea)
|
||||
@@ -269,17 +563,48 @@ class Util:
|
||||
return int(locktimea) - (locktimeb)
|
||||
|
||||
def get_lowest_valid_tx(available_utxos, will):
|
||||
"""Find the lowest valid transaction in a will by locktime.
|
||||
|
||||
Iterates through will items sorted by locktime to find the first
|
||||
transaction whose inputs are still available.
|
||||
|
||||
Args:
|
||||
available_utxos: List of available UTXOs.
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
|
||||
Note:
|
||||
This method is incomplete and currently does not return a value.
|
||||
"""
|
||||
will = sorted(will.items(), key=lambda x: x[1]["tx"].locktime)
|
||||
for txid, willitem in will.items():
|
||||
pass
|
||||
|
||||
def get_locktimes(will):
|
||||
"""Extract all unique locktime values from a will.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
|
||||
Returns:
|
||||
dict_keys: Collection of unique locktime values from the will.
|
||||
"""
|
||||
locktimes = {}
|
||||
for txid, willitem in will.items():
|
||||
locktimes[willitem["tx"].locktime] = True
|
||||
return locktimes.keys()
|
||||
|
||||
def get_lowest_locktimes(locktimes):
|
||||
"""Separate and sort locktimes into timestamp and block-height groups.
|
||||
|
||||
Locktimes below LOCKTIME_THRESHOLD are sorted as block heights;
|
||||
those above are sorted as timestamps.
|
||||
|
||||
Args:
|
||||
locktimes: Iterable of locktime values.
|
||||
|
||||
Returns:
|
||||
tuple: (sorted_timestamp_list, sorted_block_list)
|
||||
"""
|
||||
sorted_timestamp = []
|
||||
sorted_block = []
|
||||
for locktime in locktimes:
|
||||
@@ -292,18 +617,57 @@ class Util:
|
||||
return sorted(sorted_timestamp), sorted(sorted_block)
|
||||
|
||||
def get_lowest_locktimes_from_will(will):
|
||||
"""Get the lowest locktimes from a will, separated by type.
|
||||
|
||||
Convenience method that combines get_locktimes and get_lowest_locktimes.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
|
||||
Returns:
|
||||
tuple: (sorted_timestamp_list, sorted_block_list)
|
||||
"""
|
||||
return Util.get_lowest_locktimes(Util.get_locktimes(will))
|
||||
|
||||
def search_willtx_per_io(will, tx):
|
||||
"""Search for a will transaction matching a given transaction by inputs and outputs.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
tx (dict): Transaction dictionary with a 'tx' key containing the
|
||||
transaction to match.
|
||||
|
||||
Returns:
|
||||
tuple: (will_id, will_item) if found, (None, None) otherwise.
|
||||
"""
|
||||
for wid, w in will.items():
|
||||
if Util.cmp_txs(w["tx"], tx["tx"]):
|
||||
return wid, w
|
||||
return None, None
|
||||
|
||||
def invalidate_will(will):
|
||||
"""Invalidate a will.
|
||||
|
||||
Note:
|
||||
Not yet implemented.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items to invalidate.
|
||||
|
||||
Raises:
|
||||
Exception: Always raises "not implemented".
|
||||
"""
|
||||
raise Exception("not implemented")
|
||||
|
||||
def get_will_spent_utxos(will):
|
||||
"""Collect all UTXOs spent by the transactions in a will.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
|
||||
Returns:
|
||||
list: All input UTXOs from all transactions in the will.
|
||||
"""
|
||||
utxos = []
|
||||
for txid, willitem in will.items():
|
||||
utxos += willitem["tx"].inputs()
|
||||
@@ -311,6 +675,17 @@ class Util:
|
||||
return utxos
|
||||
|
||||
def utxo_to_str(utxo):
|
||||
"""Convert a UTXO to its string representation.
|
||||
|
||||
Tries multiple methods: utxo.to_str(), utxo.prevout.to_str(),
|
||||
or str() as a fallback.
|
||||
|
||||
Args:
|
||||
utxo: A UTXO object.
|
||||
|
||||
Returns:
|
||||
str: String representation of the UTXO.
|
||||
"""
|
||||
try:
|
||||
return utxo.to_str()
|
||||
except Exception:
|
||||
@@ -322,6 +697,15 @@ class Util:
|
||||
return str(utxo)
|
||||
|
||||
def cmp_utxo(utxoa, utxob):
|
||||
"""Compare two UTXOs for equality based on their string representation.
|
||||
|
||||
Args:
|
||||
utxoa: First UTXO object.
|
||||
utxob: Second UTXO object.
|
||||
|
||||
Returns:
|
||||
bool: True if both UTXOs have the same string representation.
|
||||
"""
|
||||
utxoa = Util.utxo_to_str(utxoa)
|
||||
utxob = Util.utxo_to_str(utxob)
|
||||
if utxoa == utxob:
|
||||
@@ -330,21 +714,57 @@ class Util:
|
||||
return False
|
||||
|
||||
def in_utxo(utxo, utxos):
|
||||
"""Check if a UTXO exists in a list of UTXOs.
|
||||
|
||||
Args:
|
||||
utxo: The UTXO to search for.
|
||||
utxos (list): List of UTXOs to search in.
|
||||
|
||||
Returns:
|
||||
bool: True if the UTXO is found in the list.
|
||||
"""
|
||||
for s_u in utxos:
|
||||
if Util.cmp_utxo(s_u, utxo):
|
||||
return True
|
||||
return False
|
||||
|
||||
def txid_in_utxo(txid, utxos):
|
||||
"""Check if a transaction ID exists in any UTXO's prevout.
|
||||
|
||||
Args:
|
||||
txid (str): The transaction ID to search for.
|
||||
utxos (list): List of UTXOs to search in.
|
||||
|
||||
Returns:
|
||||
bool: True if any UTXO's prevout matches the given txid.
|
||||
"""
|
||||
for s_u in utxos:
|
||||
if s_u.prevout.txid == txid:
|
||||
return True
|
||||
return False
|
||||
|
||||
def cmp_output(outputa, outputb):
|
||||
"""Compare two transaction outputs for equality by address and value.
|
||||
|
||||
Args:
|
||||
outputa: First transaction output.
|
||||
outputb: Second transaction output.
|
||||
|
||||
Returns:
|
||||
bool: True if both outputs have the same address and value.
|
||||
"""
|
||||
return outputa.address == outputb.address and outputa.value == outputb.value
|
||||
|
||||
def in_output(output, outputs):
|
||||
"""Check if an output exists in a list of outputs.
|
||||
|
||||
Args:
|
||||
output: The transaction output to search for.
|
||||
outputs (list): List of transaction outputs to search in.
|
||||
|
||||
Returns:
|
||||
bool: True if a matching output is found in the list.
|
||||
"""
|
||||
for s_o in outputs:
|
||||
if Util.cmp_output(s_o, output):
|
||||
return True
|
||||
@@ -356,6 +776,22 @@ class Util:
|
||||
# return false false different amount, different address not found
|
||||
|
||||
def din_output(out, outputs):
|
||||
"""Differentiate an output against a list of outputs by amount and address.
|
||||
|
||||
Checks whether the output's amount appears in the list, and whether
|
||||
any output with the same amount also shares the same address. Used to
|
||||
detect change outputs.
|
||||
|
||||
Args:
|
||||
out: The transaction output to check.
|
||||
outputs (list): List of transaction outputs to compare against.
|
||||
|
||||
Returns:
|
||||
tuple: (same_amount, same_address) where:
|
||||
- (True, True): same address and same amount found.
|
||||
- (True, False): same amount but different address (potential change).
|
||||
- (False, False): no matching amount found.
|
||||
"""
|
||||
same_amount = []
|
||||
for s_o in outputs:
|
||||
if int(out.value) == int(s_o.value):
|
||||
@@ -371,6 +807,22 @@ class Util:
|
||||
return False, False
|
||||
|
||||
def get_change_output(wallet, in_amount, out_amount, fee):
|
||||
"""Create a change output for a transaction if the change exceeds the dust threshold.
|
||||
|
||||
Calculates the change amount as inputs minus outputs minus fees, and
|
||||
creates a PartialTxOutput directed to a new change address if the amount
|
||||
is above the wallet's dust threshold.
|
||||
|
||||
Args:
|
||||
wallet: The Electrum wallet object.
|
||||
in_amount (int): Total input amount in satoshis.
|
||||
out_amount (int): Total output amount in satoshis.
|
||||
fee (int): Transaction fee in satoshis.
|
||||
|
||||
Returns:
|
||||
PartialTxOutput or None: A change output if change exceeds dust threshold,
|
||||
otherwise None.
|
||||
"""
|
||||
change_amount = int(in_amount - out_amount - fee)
|
||||
if change_amount > wallet.dust_threshold():
|
||||
change_addresses = wallet.get_change_addresses_for_new_transaction()
|
||||
@@ -381,6 +833,18 @@ class Util:
|
||||
return out
|
||||
|
||||
def get_current_height(network):
|
||||
"""Get the current best block height from the Electrum network.
|
||||
|
||||
Uses the minimum of the SPV-verified chain height and the server-reported
|
||||
height to discourage fee sniping. Returns 0 if the network is unavailable,
|
||||
stale, or suspiciously divergent.
|
||||
|
||||
Args:
|
||||
network: The Electrum network object.
|
||||
|
||||
Returns:
|
||||
int: The current block height, or 0 if unavailable/unreliable.
|
||||
"""
|
||||
# if no network or not up to date, just set locktime to zero
|
||||
if not network:
|
||||
return 0
|
||||
@@ -402,6 +866,16 @@ class Util:
|
||||
return height
|
||||
|
||||
def print_var(var, name="", veryverbose=False):
|
||||
"""Print detailed debug information about a variable.
|
||||
|
||||
Attempts to print various representations: str, repr, dict, dir, type,
|
||||
to_json, and __slotnames__.
|
||||
|
||||
Args:
|
||||
var: The variable to inspect.
|
||||
name (str): A label for the output header. Defaults to "".
|
||||
veryverbose (bool): Unused parameter. Defaults to False.
|
||||
"""
|
||||
print(f"---{name}---")
|
||||
if var is not None:
|
||||
try:
|
||||
@@ -436,6 +910,15 @@ class Util:
|
||||
print(f"---end {name}---")
|
||||
|
||||
def print_utxo(utxo, name=""):
|
||||
"""Print detailed debug information about a UTXO.
|
||||
|
||||
Prints the UTXO itself, its prevout, script_sig, witness, and private
|
||||
attributes (address, scriptpubkey, value_sats).
|
||||
|
||||
Args:
|
||||
utxo: The UTXO object to inspect.
|
||||
name (str): A label for the output header. Defaults to "".
|
||||
"""
|
||||
print(f"---utxo-{name}---")
|
||||
Util.print_var(utxo, name)
|
||||
Util.print_prevout(utxo.prevout, name)
|
||||
@@ -447,12 +930,29 @@ class Util:
|
||||
print(f"---utxo-end {name}---")
|
||||
|
||||
def print_prevout(prevout, name=""):
|
||||
"""Print detailed debug information about a prevout object.
|
||||
|
||||
Args:
|
||||
prevout: The prevout object to inspect.
|
||||
name (str): A label for the output header. Defaults to "".
|
||||
"""
|
||||
print(f"---prevout-{name}---")
|
||||
Util.print_var(prevout, f"{name}-prevout")
|
||||
Util.print_var(prevout._asdict())
|
||||
print(f"---prevout-end {name}---")
|
||||
|
||||
def export_meta_gui(electrum_window, title, exporter):
|
||||
"""Export data to a file via the Electrum GUI save dialog.
|
||||
|
||||
Opens a file save dialog, calls the exporter function with the chosen
|
||||
filename, and shows a success or error message.
|
||||
|
||||
Args:
|
||||
electrum_window: The Electrum main window object.
|
||||
title (str): Description of the data being exported.
|
||||
exporter (callable): A function that takes a filename and writes the
|
||||
data to it. Raises FileExportFailed on error.
|
||||
"""
|
||||
filter_ = "All files (*)"
|
||||
filename = getSaveFileName(
|
||||
parent=electrum_window,
|
||||
@@ -473,10 +973,27 @@ class Util:
|
||||
)
|
||||
|
||||
def copy(dicto, dictfrom):
|
||||
"""Copy all key-value pairs from one dictionary to another.
|
||||
|
||||
Args:
|
||||
dicto (dict): The destination dictionary.
|
||||
dictfrom (dict): The source dictionary.
|
||||
"""
|
||||
for k, v in dictfrom.items():
|
||||
dicto[k] = v
|
||||
|
||||
def fix_will_settings_tx_fees(will_settings):
|
||||
"""Migrate will settings from old 'tx_fees' key to 'baltx_fees'.
|
||||
|
||||
Renames the 'tx_fees' key to 'baltx_fees' in the will settings dictionary
|
||||
for backward compatibility.
|
||||
|
||||
Args:
|
||||
will_settings (dict): The will settings dictionary to update.
|
||||
|
||||
Returns:
|
||||
bool: True if the key was renamed, False if no migration was needed.
|
||||
"""
|
||||
tx_fees = will_settings.get("tx_fees", False)
|
||||
have_to_update = False
|
||||
if tx_fees:
|
||||
@@ -486,6 +1003,17 @@ class Util:
|
||||
return have_to_update
|
||||
|
||||
def fix_will_tx_fees(will):
|
||||
"""Migrate will transactions from old 'tx_fees' key to 'baltx_fees'.
|
||||
|
||||
Iterates through all will items and renames the 'tx_fees' key to
|
||||
'baltx_fees' in each transaction for backward compatibility.
|
||||
|
||||
Args:
|
||||
will (dict): Dictionary of will items keyed by transaction ID.
|
||||
|
||||
Returns:
|
||||
bool: True if any key was renamed, False if no migration was needed.
|
||||
"""
|
||||
have_to_update = False
|
||||
for txid, willitem in will.items():
|
||||
tx_fees = willitem.get("tx_fees", False)
|
||||
@@ -494,3 +1022,30 @@ class Util:
|
||||
del will[txid]["tx_fees"]
|
||||
have_to_update = True
|
||||
return have_to_update
|
||||
|
||||
def text_to_hex(text: str) -> str:
|
||||
"""Convert text to a hexadecimal string.
|
||||
|
||||
Args:
|
||||
text (str): The text to convert.
|
||||
|
||||
Returns:
|
||||
str: The hexadecimal representation of the text.
|
||||
"""
|
||||
hex_string = text.encode('utf-8').hex()
|
||||
return hex_string
|
||||
|
||||
|
||||
def hex_to_text(hex_string: str) -> str:
|
||||
"""Convert a hexadecimal string back to text.
|
||||
|
||||
Args:
|
||||
hex_string (str): The hexadecimal string to convert.
|
||||
|
||||
Returns:
|
||||
str: The decoded text, or an error message if the hex string is invalid.
|
||||
"""
|
||||
try:
|
||||
return bytes.fromhex(hex_string).decode('utf-8')
|
||||
except Exception:
|
||||
return "Error: Invalid hex string"
|
||||
|
||||
29
will.py
29
will.py
@@ -1,3 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Will module for the BAL Electrum plugin.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Will module for the BAL Electrum plugin.
|
||||
|
||||
import copy
|
||||
|
||||
from electrum.bitcoin import NLOCKTIME_BLOCKHEIGHT_MAX
|
||||
@@ -339,6 +347,7 @@ class Will:
|
||||
utxos = wallet.get_utxos()
|
||||
filtered_inputs = []
|
||||
prevout_to_spend = []
|
||||
current_height = Util.get_current_height(wallet.network)
|
||||
for prevout_str, ws in inputs.items():
|
||||
for w in ws:
|
||||
if w[0] not in filtered_inputs:
|
||||
@@ -348,6 +357,8 @@ class Will:
|
||||
balance = 0
|
||||
utxo_to_spend = []
|
||||
for utxo in utxos:
|
||||
if utxo.is_coinbase_output() and utxo.block_height < current_height+100:
|
||||
continue
|
||||
utxo_str = utxo.prevout.to_str()
|
||||
if utxo_str in prevout_to_spend:
|
||||
balance += inputs[utxo_str][0][2].value_sats()
|
||||
@@ -356,7 +367,7 @@ class Will:
|
||||
change_addresses = wallet.get_change_addresses_for_new_transaction()
|
||||
out = PartialTxOutput.from_address_and_value(change_addresses[0], balance)
|
||||
out.is_change = True
|
||||
locktime = Util.get_current_height(wallet.network)
|
||||
locktime = current_height
|
||||
tx = PartialTransaction.from_io(
|
||||
utxo_to_spend, [out], locktime=locktime, version=2
|
||||
)
|
||||
@@ -560,6 +571,9 @@ class Will:
|
||||
raise WillExpiredException(
|
||||
f"Will Expired {wid[0][0]}: {locktime}<{timestamp_to_check}"
|
||||
)
|
||||
else:
|
||||
from datetime import datetime
|
||||
_logger.debug(f"Will Not Expired {wid[0][0]}: {datetime.fromtimestamp(locktime).isoformat()} > {datetime.fromtimestamp(timestamp_to_check).isoformat()}")
|
||||
|
||||
# def check_all_input_spent_are_in_wallet():
|
||||
# _logger.info("check all input spent are in wallet or valid txs")
|
||||
@@ -793,9 +807,9 @@ class WillItem(Logger):
|
||||
iw = inp[1]
|
||||
self.set_anticipate(iw)
|
||||
|
||||
def check_willexecutor(self):
|
||||
def set_check_willexecutor(self,resp):
|
||||
try:
|
||||
if resp := Willexecutors.check_transaction(self._id, self.we["url"]):
|
||||
if resp :
|
||||
if "tx" in resp and resp["tx"] == str(self.tx):
|
||||
self.set_status("PUSHED")
|
||||
self.set_status("CHECKED")
|
||||
@@ -835,7 +849,12 @@ class WillItem(Logger):
|
||||
|
||||
|
||||
class WillException(Exception):
|
||||
pass
|
||||
def __init__(self,msg="WillException"):
|
||||
self.msg=msg
|
||||
Exception.__init__(self)
|
||||
def __str__(self):
|
||||
return self.msg
|
||||
|
||||
|
||||
|
||||
class WillExpiredException(WillException):
|
||||
@@ -872,8 +891,6 @@ class WillExecutorNotPresent(NotCompleteWillException):
|
||||
|
||||
class NoHeirsException(WillException):
|
||||
pass
|
||||
|
||||
|
||||
class AmountException(WillException):
|
||||
pass
|
||||
|
||||
|
||||
196
willexecutors.py
196
willexecutors.py
@@ -1,3 +1,13 @@
|
||||
"""Willexecutors module for BAL Electrum Plugin.
|
||||
|
||||
This module provides functionality to manage will executor servers that
|
||||
broadcast timelocked transactions at the appropriate locktime.
|
||||
|
||||
Classes:
|
||||
Willexecutors: Static class for managing executor list and communication
|
||||
WillExecutor: Data class representing a single will executor
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
import time
|
||||
@@ -18,8 +28,19 @@ chainname = constants.net.NET_NAME if constants.net.NET_NAME != "mainnet" else "
|
||||
|
||||
|
||||
class Willexecutors:
|
||||
"""Static class managing will executor servers.
|
||||
|
||||
Provides methods to save/load configurations, communicate via HTTP,
|
||||
push transactions, and download executor lists from remote sources.
|
||||
"""
|
||||
|
||||
def save(bal_plugin, willexecutors):
|
||||
"""Save will executor configuration to plugin settings.
|
||||
|
||||
Args:
|
||||
bal_plugin: BAL plugin instance
|
||||
willexecutors: Dictionary of executor configs keyed by URL
|
||||
"""
|
||||
_logger.debug(f"save {willexecutors},{chainname}")
|
||||
aw = bal_plugin.WILLEXECUTORS.get()
|
||||
aw[chainname] = willexecutors
|
||||
@@ -30,6 +51,18 @@ class Willexecutors:
|
||||
def get_willexecutors(
|
||||
bal_plugin, update=False, bal_window=False, force=False, task=True
|
||||
):
|
||||
"""Retrieve and update the list of available will executors.
|
||||
|
||||
Args:
|
||||
bal_plugin: BAL plugin instance
|
||||
update: If True, ping servers to refresh data
|
||||
bal_window: GUI window for user prompts
|
||||
force: Force update regardless of cached data age
|
||||
task: Run as background task if True
|
||||
|
||||
Returns:
|
||||
dict: Sorted dictionary of executor configurations
|
||||
"""
|
||||
willexecutors = bal_plugin.WILLEXECUTORS.get()
|
||||
willexecutors = willexecutors.get(chainname, {})
|
||||
to_del = []
|
||||
@@ -79,6 +112,15 @@ class Willexecutors:
|
||||
return w_sorted
|
||||
|
||||
def is_selected(willexecutor, value=None):
|
||||
"""Check or set the selection status of an executor.
|
||||
|
||||
Args:
|
||||
willexecutor: Executor configuration dictionary
|
||||
value: Optional boolean to set selection status
|
||||
|
||||
Returns:
|
||||
bool: Current selection status
|
||||
"""
|
||||
if not willexecutor:
|
||||
return False
|
||||
if value is not None:
|
||||
@@ -90,6 +132,15 @@ class Willexecutors:
|
||||
return False
|
||||
|
||||
def get_willexecutor_transactions(will, force=False):
|
||||
"""Collect transactions grouped by executor for valid, complete wills.
|
||||
|
||||
Args:
|
||||
will: Dictionary of will items keyed by ID
|
||||
force: Include already-pushed transactions
|
||||
|
||||
Returns:
|
||||
dict: Executors with their aggregated transactions
|
||||
"""
|
||||
willexecutors = {}
|
||||
for wid, willitem in will.items():
|
||||
if willitem.get_status("VALID"):
|
||||
@@ -127,12 +178,28 @@ class Willexecutors:
|
||||
def send_request(
|
||||
method, url, data=None, *, timeout=10, handle_response=None, count_reply=0
|
||||
):
|
||||
"""Send HTTP request to a will executor server.
|
||||
|
||||
Args:
|
||||
method: HTTP method (get/post)
|
||||
url: Target server URL
|
||||
data: Request payload
|
||||
timeout: Timeout in seconds
|
||||
handle_response: Response processing function
|
||||
count_reply: Retry counter for timeouts
|
||||
|
||||
Returns:
|
||||
Server response object
|
||||
|
||||
Raises:
|
||||
Exception: On connection errors or invalid method
|
||||
"""
|
||||
network = Network.get_instance()
|
||||
if not network:
|
||||
raise Exception("You are offline.")
|
||||
_logger.debug(f"<-- {method} {url} {data}")
|
||||
headers = {}
|
||||
headers["user-agent"] = f"BalPlugin v:{BalPlugin.version()}"
|
||||
headers["user-agent"] = f"BalPlugin v:{BalPlugin.__version__}"
|
||||
headers["Content-Type"] = "text/plain"
|
||||
if not handle_response:
|
||||
handle_response = Willexecutors.handle_response
|
||||
@@ -178,12 +245,28 @@ class Willexecutors:
|
||||
return response
|
||||
|
||||
def get_we_url_from_response(resp):
|
||||
"""Extract base URL from response object.
|
||||
|
||||
Args:
|
||||
resp: Response object with url attribute
|
||||
|
||||
Returns:
|
||||
str: Base URL without trailing paths
|
||||
"""
|
||||
url_slices = str(resp.url).split("/")
|
||||
if len(url_slices) > 2:
|
||||
url_slices = url_slices[:-2]
|
||||
return "/".join(url_slices)
|
||||
|
||||
async def handle_response(resp: ClientResponse):
|
||||
"""Parse JSON response from executor server.
|
||||
|
||||
Args:
|
||||
resp: aiohttp ClientResponse object
|
||||
|
||||
Returns:
|
||||
Parsed JSON data or raw text on parse failure
|
||||
"""
|
||||
r = await resp.text()
|
||||
try:
|
||||
|
||||
@@ -197,9 +280,21 @@ class Willexecutors:
|
||||
return r
|
||||
|
||||
class AlreadyPresentException(Exception):
|
||||
"""Raised when transactions already exist on executor server."""
|
||||
pass
|
||||
|
||||
def push_transactions_to_willexecutor(willexecutor):
|
||||
"""Push timelocked transactions to an executor server for broadcast.
|
||||
|
||||
Args:
|
||||
willexecutor: Dict containing url and txs keys
|
||||
|
||||
Returns:
|
||||
bool: True on success, False on failure
|
||||
|
||||
Raises:
|
||||
AlreadyPresentException: If transactions already exist
|
||||
"""
|
||||
out = True
|
||||
try:
|
||||
_logger.debug(f"{willexecutor['url']}: {willexecutor['txs']}")
|
||||
@@ -225,10 +320,24 @@ class Willexecutors:
|
||||
return out
|
||||
|
||||
def ping_servers(willexecutors):
|
||||
"""Ping all executor servers to update their information.
|
||||
|
||||
Args:
|
||||
willexecutors: Dictionary of executor configurations
|
||||
"""
|
||||
for url, we in willexecutors.items():
|
||||
Willexecutors.get_info_task(url, we)
|
||||
|
||||
def get_info_task(url, willexecutor):
|
||||
"""Fetch current information from a single executor server.
|
||||
|
||||
Args:
|
||||
url: Executor server URL
|
||||
willexecutor: Configuration dict to update
|
||||
|
||||
Returns:
|
||||
Updated willexecutor dict with status, base_fee, address
|
||||
"""
|
||||
w = None
|
||||
try:
|
||||
_logger.info("GETINFO_WILLEXECUTOR")
|
||||
@@ -249,6 +358,14 @@ class Willexecutors:
|
||||
return willexecutor
|
||||
|
||||
def initialize_willexecutor(willexecutor, url, status=None, old_willexecutor={}):
|
||||
"""Initialize or merge executor configuration preserving user settings.
|
||||
|
||||
Args:
|
||||
willexecutor: New executor configuration dict
|
||||
url: Executor server URL
|
||||
status: Optional status override
|
||||
old_willexecutor: Previous config to preserve user preferences
|
||||
"""
|
||||
willexecutor["url"] = url
|
||||
if status is not None:
|
||||
willexecutor["status"] = status
|
||||
@@ -260,7 +377,15 @@ class Willexecutors:
|
||||
|
||||
|
||||
|
||||
def download_list(bal_plugin,old_willexecutors):
|
||||
def download_list(old_willexecutors):
|
||||
"""Download latest executor list from remote source.
|
||||
|
||||
Args:
|
||||
old_willexecutors: Existing configs to merge with new list
|
||||
|
||||
Returns:
|
||||
dict: Merged executor configurations
|
||||
"""
|
||||
try:
|
||||
willexecutors = Willexecutors.send_request(
|
||||
"get",
|
||||
@@ -280,7 +405,12 @@ class Willexecutors:
|
||||
_logger.error(f"Failed to download willexecutors list: {e}")
|
||||
return {}
|
||||
|
||||
def get_willexecutors_list_from_json(bal_plugin):
|
||||
def get_willexecutors_list_from_json():
|
||||
"""Load executor list from local willexecutors.json file.
|
||||
|
||||
Returns:
|
||||
dict: Executor configurations from JSON file
|
||||
"""
|
||||
try:
|
||||
with open("willexecutors.json") as f:
|
||||
willexecutors = json.load(f)
|
||||
@@ -295,6 +425,15 @@ class Willexecutors:
|
||||
return {}
|
||||
|
||||
def check_transaction(txid, url):
|
||||
"""Check if a transaction exists on executor server.
|
||||
|
||||
Args:
|
||||
txid: Transaction ID string
|
||||
url: Executor server URL
|
||||
|
||||
Returns:
|
||||
Server response about transaction existence
|
||||
"""
|
||||
_logger.debug(f"{url}:{txid}")
|
||||
try:
|
||||
w = Willexecutors.send_request(
|
||||
@@ -306,10 +445,31 @@ class Willexecutors:
|
||||
raise e
|
||||
|
||||
def compute_id(willexecutor):
|
||||
"""Compute unique identifier for an executor.
|
||||
|
||||
Args:
|
||||
willexecutor: Executor configuration dict
|
||||
|
||||
Returns:
|
||||
str: Unique ID combining URL and chain name
|
||||
"""
|
||||
return "{}-{}".format(willexecutor.get("url"), willexecutor.get("chain"))
|
||||
|
||||
|
||||
class WillExecutor:
|
||||
"""Data class representing a single will executor server.
|
||||
|
||||
Attributes:
|
||||
url: Executor server URL
|
||||
base_fee: Fixed fee in satoshis
|
||||
chain: Bitcoin chain name
|
||||
info: Additional executor information
|
||||
version: Plugin version compatibility
|
||||
status: Connection status
|
||||
is_selected: User selection flag
|
||||
promo_code: Promotional discount code
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url,
|
||||
@@ -321,6 +481,18 @@ class WillExecutor:
|
||||
is_selected=False,
|
||||
promo_code="",
|
||||
):
|
||||
"""Initialize a new WillExecutor instance.
|
||||
|
||||
Args:
|
||||
url: Executor server URL
|
||||
base_fee: Fixed fee in satoshis
|
||||
chain: Bitcoin chain name
|
||||
info: Additional executor information
|
||||
version: Plugin version compatibility
|
||||
status: Connection status (OK/Ko)
|
||||
is_selected: Whether user has selected this executor
|
||||
promo_code: Promotional discount code
|
||||
"""
|
||||
self.url = url
|
||||
self.base_fee = base_fee
|
||||
self.chain = chain
|
||||
@@ -332,6 +504,14 @@ class WillExecutor:
|
||||
self.id = self.compute_id()
|
||||
|
||||
def from_dict(d):
|
||||
"""Create WillExecutor instance from a dictionary.
|
||||
|
||||
Args:
|
||||
d: Dictionary containing executor data fields
|
||||
|
||||
Returns:
|
||||
WillExecutor: New instance with defaults for missing fields
|
||||
"""
|
||||
return WillExecutor(
|
||||
url=d.get("url", "http://localhost:8000"),
|
||||
base_fee=d.get("base_fee", 1000),
|
||||
@@ -344,6 +524,11 @@ class WillExecutor:
|
||||
)
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert WillExecutor to dictionary representation.
|
||||
|
||||
Returns:
|
||||
dict: Serializable representation excluding computed fields
|
||||
"""
|
||||
return {
|
||||
"url": self.url,
|
||||
"base_fee": self.base_fee,
|
||||
@@ -354,4 +539,9 @@ class WillExecutor:
|
||||
}
|
||||
|
||||
def compute_id(self):
|
||||
"""Generate unique identifier for this executor.
|
||||
|
||||
Returns:
|
||||
str: Unique ID from URL and chain name
|
||||
"""
|
||||
return f"{self.url}-{self.chain}"
|
||||
|
||||
Reference in New Issue
Block a user