| 1280 | } |
| 1281 | |
| 1282 | static struct command_result *currency_done(struct command *cmd, |
| 1283 | const char *method, |
| 1284 | const char *buf, |
| 1285 | const jsmntok_t *result, |
| 1286 | struct currency_time *ctime) |
| 1287 | { |
| 1288 | struct bkpr *bkpr = bkpr_of(cmd->plugin); |
| 1289 | double rate; |
| 1290 | const char *err; |
| 1291 | |
| 1292 | err = json_scan(cmd, buf, result, "{rate:%}", |
| 1293 | JSON_SCAN(json_to_double, &rate)); |
| 1294 | if (err) { |
| 1295 | plugin_log(cmd->plugin, LOG_BROKEN, |
| 1296 | "Invalid currencyrate return '%.*s': %s", |
| 1297 | json_tok_full_len(result), |
| 1298 | json_tok_full(buf, result), err); |
| 1299 | /* Make sure they didn't change currency while we were out! */ |
| 1300 | } else if (bkpr->currency == ctime->currency) { |
| 1301 | char *val; |
| 1302 | const char **key; |
| 1303 | u64 raw_rate = (u64)(rate * ratefactor(bkpr->currency)); |
| 1304 | /* Can we extend previous entry */ |
| 1305 | u64 ts = ctime->timestamp + 1; |
| 1306 | struct currencyrate *crate |
| 1307 | = uintmap_before(bkpr->currency_rates, &ts); |
| 1308 | |
| 1309 | if (crate) { |
| 1310 | u64 crate_end = ts + crate->duration; |
| 1311 | /* If we raced, it might already be there! */ |
| 1312 | if (crate_end > ctime->timestamp) |
| 1313 | goto out; |
| 1314 | |
| 1315 | /* Reuse if it's recent, and the same rate. |
| 1316 | * (Recent check avoid glossing over failures, if we |
| 1317 | * couldn't get reliable data). */ |
| 1318 | if (raw_rate == crate->raw_rate |
| 1319 | && crate_end + CURRENCYRATE_TOLERANCE_SECONDS > ctime->timestamp) { |
| 1320 | uintmap_del(bkpr->currency_rates, ts); |
| 1321 | crate->duration = ctime->timestamp - ts + 1; |
| 1322 | } else { |
| 1323 | crate = NULL; |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | if (!crate) { |
| 1328 | ts = ctime->timestamp; |
| 1329 | crate = tal(bkpr->currency_rates, struct currencyrate); |
| 1330 | crate->raw_rate = raw_rate; |
| 1331 | crate->duration = 1; |
| 1332 | } |
| 1333 | uintmap_add(bkpr->currency_rates, ts, crate); |
| 1334 | val = tal_fmt(tmpctx, "%"PRIu64":%u", |
| 1335 | crate->raw_rate, crate->duration); |
| 1336 | key = mkdatastorekey(tmpctx, |
| 1337 | "bookkeeper", |
| 1338 | "currencyrate", |
| 1339 | ctime->currency->name, |
nothing calls this directly
no test coverage detected