1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! Hash-based duplicate transaction detection.
//!
//! Mirrors Python beancount's `beancount.plugins.noduplicates`, which uses
//! `beancount.core.compare.hash_entry` to identify structurally identical
//! transactions. `hash_entry` hashes every field that contributes to a
//! transaction's structural identity: flag, payee, narration, tags, links,
//! and each posting's account, units, cost, price, and flag. Metadata is
//! deliberately excluded (beancount's `hash_entry` passes `exclude_meta=True`).
//!
//! The hash helpers below use exhaustive struct destructuring so that adding
//! a field to `TransactionData`, `PostingData`, `CostData`, `AmountData`, or
//! `PriceAnnotationData` causes a compile error here — forcing whoever adds
//! the field to explicitly decide whether it contributes to structural
//! identity (add to the hash) or not (bind with `_` and document why).
use crate::types::{
AmountData, CostData, DirectiveData, PluginError, PluginInput, PluginOutput, PostingData,
PriceAnnotationData, TransactionData,
};
use super::super::NativePlugin;
/// Plugin that detects duplicate transactions based on hash.
pub struct NoDuplicatesPlugin;
impl NativePlugin for NoDuplicatesPlugin {
fn name(&self) -> &'static str {
"noduplicates"
}
fn description(&self) -> &'static str {
"Hash-based duplicate transaction detection"
}
fn process(&self, input: PluginInput) -> PluginOutput {
use std::collections::HashSet;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// Sentinel bytes used to discriminate `None` from `Some` before each
// optional component. Otherwise `(None, Some(x))` and `(Some(x), None)`
// could collide for adjacent fields. Python's tuple hash achieves the
// equivalent via `hash(None)` being a distinct fixed value.
const ABSENT: u8 = 0;
const PRESENT: u8 = 1;
fn hash_amount<H: Hasher>(amount: &AmountData, hasher: &mut H) {
let AmountData { number, currency } = amount;
number.hash(hasher);
currency.hash(hasher);
}
fn hash_cost<H: Hasher>(cost: &CostData, hasher: &mut H) {
let CostData {
number_per,
number_total,
currency,
date,
label,
merge,
} = cost;
number_per.hash(hasher);
number_total.hash(hasher);
currency.hash(hasher);
date.hash(hasher);
label.hash(hasher);
merge.hash(hasher);
}
fn hash_price<H: Hasher>(price: &PriceAnnotationData, hasher: &mut H) {
let PriceAnnotationData {
is_total,
amount,
number,
currency,
} = price;
is_total.hash(hasher);
match amount {
Some(a) => {
PRESENT.hash(hasher);
hash_amount(a, hasher);
}
None => ABSENT.hash(hasher),
}
number.hash(hasher);
currency.hash(hasher);
}
fn hash_posting<H: Hasher>(posting: &PostingData, hasher: &mut H) {
// Destructure so any future field added to `PostingData` causes a
// compile error here and the maintainer must explicitly decide
// whether it's part of structural identity.
let PostingData {
account,
units,
cost,
price,
flag,
// Metadata is intentionally NOT hashed — matches beancount's
// hash_entry(exclude_meta=True) default. Bind to `_` so adding
// a new field in the future is still a compile error.
metadata: _,
} = posting;
account.hash(hasher);
match units {
Some(u) => {
PRESENT.hash(hasher);
hash_amount(u, hasher);
}
None => ABSENT.hash(hasher),
}
match cost {
Some(c) => {
PRESENT.hash(hasher);
hash_cost(c, hasher);
}
None => ABSENT.hash(hasher),
}
match price {
Some(p) => {
PRESENT.hash(hasher);
hash_price(p, hasher);
}
None => ABSENT.hash(hasher),
}
flag.hash(hasher);
}
fn hash_transaction(date: &str, txn: &TransactionData) -> u64 {
// Destructure so any future field added to `TransactionData`
// causes a compile error here.
let TransactionData {
flag,
payee,
narration,
tags,
links,
// Metadata is intentionally NOT hashed — matches beancount's
// hash_entry(exclude_meta=True) default.
metadata: _,
postings,
} = txn;
let mut hasher = DefaultHasher::new();
date.hash(&mut hasher);
flag.hash(&mut hasher);
payee.hash(&mut hasher);
narration.hash(&mut hasher);
// Tags and links are unordered sets in beancount (`frozenset`),
// so:
// 1. Sort + dedup so the hash is stable regardless of parser
// order and collapses any accidental duplicates the parser
// might emit (matching beancount set semantics).
// 2. Each collection is prefixed with its length so the two
// streams can't be merged or swapped without changing the
// resulting hash — e.g. `tags={a,b}, links={}` no longer
// collides with `tags={a}, links={b}`.
let mut sorted_tags: Vec<&String> = tags.iter().collect();
sorted_tags.sort();
sorted_tags.dedup();
sorted_tags.len().hash(&mut hasher);
for tag in sorted_tags {
tag.hash(&mut hasher);
}
let mut sorted_links: Vec<&String> = links.iter().collect();
sorted_links.sort();
sorted_links.dedup();
sorted_links.len().hash(&mut hasher);
for link in sorted_links {
link.hash(&mut hasher);
}
// Prefix postings with their count so the posting stream can't
// collide with trailing fields of the set streams above.
postings.len().hash(&mut hasher);
for posting in postings {
hash_posting(posting, &mut hasher);
}
hasher.finish()
}
let mut seen: HashSet<u64> = HashSet::new();
let mut errors = Vec::new();
for wrapper in &input.directives {
if let DirectiveData::Transaction(txn) = &wrapper.data {
let hash = hash_transaction(&wrapper.date, txn);
if !seen.insert(hash) {
errors.push(PluginError::error(format!(
"Duplicate transaction: {} \"{}\"",
wrapper.date, txn.narration
)));
}
}
}
PluginOutput {
directives: input.directives,
errors,
}
}
}