diff --git a/.gitignore b/.gitignore index dbc9f07ab..9fbf5b058 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ *.gcno *.gcda *.mo +*.blg +*.bbl .dirstamp m4/*.m4 doc/coverage/ @@ -34,7 +36,8 @@ GRTAGS GTAGS *.swp src/include/taler_error_codes.h -src/lib/test_exchange_api +src/testing/test_exchange_api_rsa +src/testing/test_exchange_api_cs doc/doxygen/doxygen_sqlite3.db src/auditor/taler-auditor-dbinit src/auditor/taler-auditor-sign @@ -71,6 +74,9 @@ src/exchange-tools/taler-wire src/exchangedb/perf-exchangedb src/benchmark/taler-exchange-benchmark src/benchmark/auditor.in +src/benchmark/exchange_benchmark_home/.local/share/taler/exchange-offline/ +src/benchmark/exchange_benchmark_home/.local/share/taler/exchange-secmod-eddsa/ +src/benchmark/exchange_benchmark_home/.local/share/taler/exchange-secmod-rsa/ src/benchmark/exchange_benchmark_home/.local/share/taler/exchange/live-keys/* src/benchmark/exchange_benchmark_home/.local/share/taler/auditors/ src/benchmark/exchange_benchmark_home/.local/share/taler/auditor/ @@ -110,9 +116,11 @@ doc/manual/manual.vr doc/prebuilt/* contrib/taler-exchange.tag doxygen-doc/ -src/testing/test_exchange_api_keys_cherry_picking +src/testing/test_exchange_api_keys_cherry_picking_cs +src/testing/test_exchange_api_keys_cherry_picking_rsa src/auditor/taler-auditor-sync src/auditor/taler-wire-auditor +src/auditor/generate_auditordb_home/ contrib/auditor-report.aux contrib/auditor-report.log contrib/auditor-report.tex @@ -120,8 +128,10 @@ contrib/auditor-report.pdf src/bank-lib/taler-bank-transfer src/bank-lib/test_bank_api_twisted src/testing/test_exchange_api -src/testing/test_auditor_api -src/testing/test_exchange_api_overlapping_keys_bug +src/testing/test_auditor_api_cs +src/testing/test_auditor_api_rsa +src/testing/test_exchange_api_overlapping_keys_bug_cs +src/testing/test_exchange_api_overlapping_keys_bug_rsa src/testing/test_exchange_api_home/.local/share/taler/exchange/revocations/ src/wire-plugins/test_wire_plugin_legacy_taler_bank uncrustify.cfg diff --git a/contrib/microhttpd.tag b/contrib/microhttpd.tag index 831e1c4e4..018723697 100644 --- a/contrib/microhttpd.tag +++ b/contrib/microhttpd.tag @@ -172,6 +172,30 @@ microhttpd.h + + #define + MHD_HTTP_METHOD_GET + microhttpd.h + + + + #define + MHD_HTTP_METHOD_POST + microhttpd.h + + + + #define + MHD_HTTP_METHOD_PUT + microhttpd.h + + + + #define + MHD_HTTP_METHOD_DELETE + microhttpd.h + + int MHD_AccessHandlerCallback diff --git a/doc/cbdc-it/agsm-mod.bst b/doc/cbdc-it/agsm-mod.bst new file mode 100644 index 000000000..ac1bbd052 --- /dev/null +++ b/doc/cbdc-it/agsm-mod.bst @@ -0,0 +1,1375 @@ +% BibTeX standard bibliography style `agsm' (one of the harvard family) + % version 0.99a for BibTeX versions 0.99a or later, LaTeX version 2.09. + % Copyright (C) 1991, all rights reserved. + % Copying of this file is authorized only if either + % (1) you make absolutely no changes to your copy, including name, or + % (2) if you do make changes, you name it something other than + % btxbst.doc, plain.bst, unsrt.bst, alpha.bst, abbrv.bst, agsm.bst, + % dcu.bst or kluwer.bst. + % This restriction helps ensure that all standard styles are identical. + % The file harvard.tex has the documentation for this style. + +% ACKNOWLEDGEMENT: +% This document is a modified version of alpha.bst to which it owes much of +% its functionality. + +% AUTHOR +% Peter Williams, Key Centre for Design Quality, Sydney University +% e-mail: peterw@archsci.arch.su.oz.au + +ENTRY + { address + author + booktitle + chapter + edition + editor + howpublished + institution + journal + key + month + note + number + organization + pages + publisher + school + series + title + type + URL + volume + year + } + { field.used etal.allowed etal.required} %%%XXX change + { extra.label sort.label list.year } + +INTEGERS { output.state before.all mid.sentence after.sentence after.block } + +FUNCTION {init.state.consts} +{ #0 'before.all := + #1 'mid.sentence := + #2 'after.sentence := + #3 'after.block := +} + +STRINGS { s t f } + +FUNCTION {output.nonnull} +{ 's := + output.state mid.sentence = + { ", " * write$ } + { output.state after.block = + { add.period$ write$ + newline$ + "\newblock " write$ + } + { output.state before.all = + 'write$ + { add.period$ " " * write$ } + if$ + } + if$ + mid.sentence 'output.state := + } + if$ + s +} + +FUNCTION {output} +{ duplicate$ empty$ + 'pop$ + 'output.nonnull + if$ +} + +FUNCTION {output.check} +{ 't := + duplicate$ empty$ + { pop$ "empty " t * " in " * cite$ * warning$ } + 'output.nonnull + if$ +} + +FUNCTION {item.check} +{ 't := + empty$ + { "empty " t * " in " * cite$ * warning$ } + { skip$ } + if$ +} + +FUNCTION {fin.entry} +{ add.period$ + write$ + newline$ +} + +FUNCTION {new.block} +{ output.state before.all = + 'skip$ + { after.block 'output.state := } + if$ +} + +FUNCTION {not} +{ { #0 } + { #1 } + if$ +} + +FUNCTION {and} +{ 'skip$ + { pop$ #0 } + if$ +} + +FUNCTION {or} +{ { pop$ #1 } + 'skip$ + if$ +} + +FUNCTION {field.or.null} +{ duplicate$ empty$ + { pop$ "" } + 'skip$ + if$ +} + +FUNCTION {emphasize} +{ duplicate$ empty$ + { pop$ "" } + { "{\em " swap$ * "}" * } + if$ +} + +FUNCTION {embolden} +{ duplicate$ empty$ + { pop$ "" } + { "{\bf " swap$ * "}" * } + if$ +} + +%%ORIGINAL KEPT HERE FOR REFERENCE: +%%FUNCTION {quote} +%%{ duplicate$ empty$ +%% { pop$ "" } +%% { "`" swap$ * "'" * } +%% if$ +%%} + +%%USE GUILLEMETS +FUNCTION {quote} +{ duplicate$ empty$ + { pop$ "" } + { "«" swap$ * "»" * } + if$ +} +%%END USE GUILLEMETS + +FUNCTION {write.url} +{ URL empty$ + { skip$ } + { "\newline\harvardurl{" URL * "}" * write$ newline$ } + if$ +} + +INTEGERS { nameptr namesleft numnames } + +FUNCTION {format.names} +{ 's := + 'f := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr f format.name$ 't := + nameptr #1 > + { namesleft #1 > + { ", " * t * } + { t "others" = + { " et~al." * } + { " \harvardand\ " * t * } + if$ + } + if$ + } + 't + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {format.authors} +{ author empty$ + { "" } + { "{vv~}{ll}{, jj}{, f.}" author format.names } + if$ +} + +FUNCTION {format.editors} +{ editor empty$ + { "" } + { "{vv~}{ll}{, jj}{, f.}" editor format.names + editor num.names$ #1 > + { ", eds" * } + { ", ed." * } + if$ + } + if$ +} + +FUNCTION {format.editors.reverse} +{ editor empty$ + { "" } + { "{f.~}{vv~}{ll}{, jj}" editor format.names + editor num.names$ #1 > + { ", eds" * } + { ", ed." * } + if$ + } + if$ +} + +%%ORIGINAL KEPT HERE FOR REFERENCE: +%%FUNCTION {format.title} +%%{ title empty$ +%% { "" } +%% { title "t" change.case$ } +%% if$ +%%} + +%%REMOVE SINGLE QUOTES +FUNCTION {format.title} +{ title empty$ + { "" } + { title "t" change.case$ quote} + if$ +} +%%END REMOVE SINGLE QUOTES + +FUNCTION {n.dashify} +{ 't := + "" + { t empty$ not } + { t #1 #1 substring$ "-" = + { t #1 #2 substring$ "--" = not + { "--" * + t #2 global.max$ substring$ 't := + } + { { t #1 #1 substring$ "-" = } + { "-" * + t #2 global.max$ substring$ 't := + } + while$ + } + if$ + } + { t #1 #1 substring$ * + t #2 global.max$ substring$ 't := + } + if$ + } + while$ +} + +FUNCTION {format.btitle} +{ title emphasize +} + +FUNCTION {tie.or.space.connect} +{ duplicate$ text.length$ #3 < + { "~" } + { " " } + if$ + swap$ * * +} + +FUNCTION {either.or.check} +{ empty$ + 'pop$ + { "can't use both " swap$ * " fields in " * cite$ * warning$ } + if$ +} + +FUNCTION {format.bvolume} +{ volume empty$ + { "" } + { "Vol." volume tie.or.space.connect + series empty$ + 'skip$ + { " of " * series emphasize * } + if$ + "volume and number" number either.or.check + } + if$ +} + +FUNCTION {format.number.series} +{ volume empty$ + { number empty$ + { series field.or.null } + { output.state mid.sentence = + { "number" } + { "Number" } + if$ + number tie.or.space.connect + series empty$ + { "there's a number but no series in " cite$ * warning$ } + { " {\em in} " * series quote * } + if$ + } + if$ + } + { "" } + if$ +} + +FUNCTION {format.edition} +{ edition empty$ + { "" } + { output.state mid.sentence = + { edition "l" change.case$ " edn" * } + { edition "t" change.case$ " edn" * } + if$ + } + if$ +} + +INTEGERS { multiresult } + +FUNCTION {multi.page.check} +{ 't := + #0 'multiresult := + { multiresult not + t empty$ not + and + } + { t #1 #1 substring$ + duplicate$ "-" = + swap$ duplicate$ "," = + swap$ "+" = + or or + { #1 'multiresult := } + { t #2 global.max$ substring$ 't := } + if$ + } + while$ + multiresult +} + +FUNCTION {format.pages} +{ pages empty$ + { "" } + { pages multi.page.check + { "pp.~" pages n.dashify * } + { "p.~" pages * } + if$ + } + if$ +} + +FUNCTION {format.vol.num.pages} +{ volume embolden field.or.null + number empty$ + 'skip$ + { "(" number * ")" * * + volume empty$ + { "there's a number but no volume in " cite$ * warning$ } + 'skip$ + if$ + } + if$ + pages empty$ + 'skip$ + { duplicate$ empty$ + { pop$ format.pages } + { ",~" * pages n.dashify * } + if$ + } + if$ +} + +FUNCTION {format.chapter.pages} +{ chapter empty$ + 'format.pages + { type empty$ + { "chapter" } + { type "l" change.case$ } + if$ + chapter tie.or.space.connect + pages empty$ + 'skip$ + { ", " * format.pages * } + if$ + } + if$ +} + +%%REMOVE ITALICS FROM WORD "IN" +FUNCTION {format.in.ed.booktitle} +{ booktitle empty$ + { "" } + { editor empty$ + %%{ "{\em in} " booktitle * } ORIGINAL + { "{in} " booktitle * } + %%{ "{\em in} " format.editors.reverse * ", " * booktitle * } ORIGINAL + { "{in} " format.editors.reverse * ", " * booktitle * } + if$ + } + if$ +} +%%END REMOVE ITALICS FROM WORD "IN" + +FUNCTION {empty.misc.check} +{ author empty$ title empty$ howpublished empty$ + month empty$ year empty$ note empty$ + and and and and and + key empty$ not and + { "all relevant fields are empty in " cite$ * warning$ } + 'skip$ + if$ +} + +FUNCTION {format.thesis.type} +{ type empty$ + 'skip$ + { pop$ + type "t" change.case$ + } + if$ +} + +FUNCTION {format.tr.number} +{ type empty$ + { "Technical Report" } + 'type + if$ + number empty$ + { "t" change.case$ } + { number tie.or.space.connect } + if$ +} + +FUNCTION {format.article.crossref} +{ key empty$ + { journal empty$ + { "need key or journal for " cite$ * " to crossref " * crossref * + warning$ + "" + } + { "in {\em " journal * "\/} \cite{" * crossref * "}" *} + if$ + } + { "{\em in} \citeasnoun{" crossref * "}" * } + if$ + +} + +FUNCTION {format.book.crossref} +{ volume empty$ + { "empty volume in " cite$ * "'s crossref of " * crossref * warning$ + "in " + } + { "Vol." volume tie.or.space.connect + " of " * + } + if$ + editor empty$ + editor field.or.null author field.or.null = + or + { key empty$ + { series empty$ + { "need editor, key, or series for " cite$ * " to crossref " * + crossref * warning$ + "" * + } + { "{\em " * series * "\/} \cite{" * crossref * "}" *} + if$ + } + { " \citeasnoun{" * crossref * "}" * } + if$ + } + { " \citeasnoun{" * crossref * "}" * } + if$ +} + +FUNCTION {format.incoll.inproc.crossref} +{ editor empty$ + editor field.or.null author field.or.null = + or + { key empty$ + { booktitle empty$ + { "need editor, key, or booktitle for " cite$ * " to crossref " * + crossref * warning$ + "" + } + { "in {\em " booktitle * "\/}" * " \cite{" * crossref * "}" *} + + if$ + } + { "{\em in} \citeasnoun{" crossref * "}" * } + if$ + } + { "{\em in} \citeasnoun{" crossref * "}" * } + if$ + +} + +INTEGERS { len } + +FUNCTION {chop.word} +{ 's := + 'len := + s #1 len substring$ = + { s len #1 + global.max$ substring$ } + 's + if$ +} + +INTEGERS { ind tsslen } + +STRINGS { tss ret rss istr } + +FUNCTION {replace.substring}{ + 'rss := + 'tss := + 'istr := + "" 'ret := + tss text.length$ 'tsslen := + #1 'ind := + { istr ind tsslen substring$ "" = not } + { istr ind tsslen substring$ tss = + { ret rss * 'ret := + ind tsslen + 'ind := + } + { ret istr ind #1 substring$ * 'ret := + ind #1 + 'ind := + } + if$ + } + while$ + ret +} + +FUNCTION {format.lab.names.abbr} +{ 's := + s num.names$ 'numnames := + numnames #1 > + { numnames #2 > + { s #1 "{vv~}{ll}" format.name$ " et~al." * } + { s #2 "{ff }{vv }{ll}{ jj}" format.name$ "others" = + { s #1 "{vv~}{ll}" format.name$ " et~al." * } + { s #1 "{vv~}{ll}" format.name$ " \harvardand\ " * + s #2 "{vv~}{ll}" format.name$ * + } + if$ + } + if$ + } + { s #1 "{vv~}{ll}" format.name$ } + if$ +} + +FUNCTION {format.lab.names.full} +{ 's := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr "{vv~}{ll}" format.name$ 't := + nameptr #1 > + { namesleft #1 > + { ", " * t * } + { t "others" = + { " et~al." * } + { " \harvardand\ " * t * } + if$ + } + if$ + } + 't + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +INTEGERS { author.field editor.field organization.field title.field key.field } + +FUNCTION {init.field.constants} +{ #0 'author.field := + #1 'editor.field := + #2 'organization.field := + #3 'title.field := + #4 'key.field := +} + +FUNCTION {make.list.label} +{ author.field field.used = + { format.authors } + { editor.field field.used = + { format.editors } + { organization.field field.used = + { "The " #4 organization chop.word #3 text.prefix$ } + { title.field field.used = + { format.btitle } + { key.field field.used = + { key #3 text.prefix$ } + { "Internal error :001 on " cite$ * " label" * warning$ } + if$ + } + if$ + } + if$ + } + if$ + } + if$ +} + +FUNCTION {make.full.label} +{ author.field field.used = + { author format.lab.names.full } + { editor.field field.used = + { editor format.lab.names.full } + { organization.field field.used = + { "The " #4 organization chop.word #3 text.prefix$ } + { title.field field.used = + { format.btitle } + { key.field field.used = + { key #3 text.prefix$ } + { "Internal error :001 on " cite$ * " label" * warning$ } + if$ + } + if$ + } + if$ + } + if$ + } + if$ +} + +FUNCTION {make.abbr.label} %%%XXX change +{ + etal.allowed + { author.field field.used = + { author format.lab.names.abbr } + { editor.field field.used = + { editor format.lab.names.abbr } + { organization.field field.used = + { "The " #4 organization chop.word #3 text.prefix$ } + { title.field field.used = + { format.btitle } + { key.field field.used = + { key #3 text.prefix$ } + {"Internal error :001 on " cite$ * " label" * warning$ } + if$ + } + if$ + } + if$ + } + if$ + } + if$ + } + { make.full.label } + if$ +} + +FUNCTION {output.bibitem} +{ newline$ + etal.allowed %%%XXX change + etal.required + and + { + "\harvarditem[" write$ + make.abbr.label write$ + "]{" write$ + } + { + "\harvarditem{" write$ + } + if$ + make.full.label write$ + "}{" write$ + list.year write$ + "}{" write$ + cite$ write$ + "}" write$ + newline$ + "" + before.all 'output.state := +} + +FUNCTION {list.label.output} +{ make.list.label " " * write$ +} + +FUNCTION {article} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author "author" item.check + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + crossref missing$ + { journal emphasize "journal" duplicate$ item.check + " " * format.vol.num.pages * output + } + { format.article.crossref output.nonnull + format.pages output + } + if$ + new.block + note output + fin.entry + write.url +} + +FUNCTION {book} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author empty$ + { editor "author and editor" item.check } + { crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + title.field field.used = + { skip$ } + { format.btitle "title" output.check } + if$ + crossref missing$ + { format.bvolume output + format.number.series output + format.edition output + publisher "publisher" output.check + address output + } + { format.book.crossref output.nonnull + format.edition output + } + if$ + new.block + note output + fin.entry + write.url +} + +FUNCTION {booklet} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + howpublished output + address output + new.block + note output + fin.entry + write.url +} + +FUNCTION {inbook} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author empty$ + { editor "author and editor" item.check } + { crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + title.field field.used = + { skip$ } + { format.btitle "title" output.check } + if$ + crossref missing$ + { format.bvolume output + format.number.series output + format.edition output + publisher "publisher" output.check + address output + } + { format.book.crossref output.nonnull + format.edition output + } + if$ + format.chapter.pages "chapter and pages" output.check + new.block + note output + fin.entry + write.url +} + +FUNCTION {incollection} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + author "author" item.check + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + format.edition output + format.bvolume output + format.number.series output + publisher "publisher" output.check + address output + } + { format.incoll.inproc.crossref output.nonnull + } + if$ + format.chapter.pages output + new.block + note output + fin.entry + write.url +} + +FUNCTION {inproceedings} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + author "author" item.check + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + format.bvolume output + format.number.series output + address empty$ + { organization output + publisher output + } + { organization output + publisher output + address output.nonnull + } + if$ + } + { format.incoll.inproc.crossref output.nonnull + } + if$ + format.pages output + new.block + note output + fin.entry + write.url +} + +FUNCTION {conference} { inproceedings } + +FUNCTION {manual} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.btitle "title" output.check } + if$ + format.edition output + author empty$ + { organization empty$ + { address output } + 'skip$ + if$ + } + { organization output + address output + } + if$ + new.block + note output + fin.entry + write.url +} + +FUNCTION {mastersthesis} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author "author" item.check + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + "Master's thesis" format.thesis.type output.nonnull + school "school" output.check + address output + new.block + note output + fin.entry + write.url +} + +FUNCTION {misc} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.title output } + if$ + howpublished output + new.block + note output + fin.entry + write.url + empty.misc.check +} + +FUNCTION {phdthesis} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author "author" item.check + title.field field.used = + { skip$ } + { title "title" output.check } + if$ + "PhD thesis" format.thesis.type output.nonnull + school "school" output.check + address output + new.block + note output + fin.entry + write.url +} + +FUNCTION {proceedings} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + title.field field.used = + { skip$ } + { format.btitle "title" output.check } + if$ + format.bvolume output + format.number.series output + address empty$ + { editor empty$ + { skip$ } + { organization output + } + if$ + publisher output + } + { editor empty$ + 'skip$ + { organization output } + if$ + publisher output + address output.nonnull + } + if$ + new.block + note output + fin.entry + write.url +} + +FUNCTION {techreport} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author "author" item.check + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + format.tr.number output.nonnull + institution "institution" output.check + address output + new.block + note output + fin.entry + write.url +} + +FUNCTION {unpublished} +{ output.bibitem + list.label.output + " \harvardyearleft " list.year * "\harvardyearright " * output.nonnull + author "author" item.check + title.field field.used = + { skip$ } + { format.title "title" output.check } + if$ + new.block + note "note" output.check + fin.entry + write.url +} + +FUNCTION {default.type} { misc } + +MACRO {jan} {"January"} + +MACRO {feb} {"February"} + +MACRO {mar} {"March"} + +MACRO {apr} {"April"} + +MACRO {may} {"May"} + +MACRO {jun} {"June"} + +MACRO {jul} {"July"} + +MACRO {aug} {"August"} + +MACRO {sep} {"September"} + +MACRO {oct} {"October"} + +MACRO {nov} {"November"} + +MACRO {dec} {"December"} + +MACRO {acmcs} {"ACM Computing Surveys"} + +MACRO {acta} {"Acta Informatica"} + +MACRO {cacm} {"Communications of the ACM"} + +MACRO {ibmjrd} {"IBM Journal of Research and Development"} + +MACRO {ibmsj} {"IBM Systems Journal"} + +MACRO {ieeese} {"IEEE Transactions on Software Engineering"} + +MACRO {ieeetc} {"IEEE Transactions on Computers"} + +MACRO {ieeetcad} + {"IEEE Transactions on Computer-Aided Design of Integrated Circuits"} + +MACRO {ipl} {"Information Processing Letters"} + +MACRO {jacm} {"Journal of the ACM"} + +MACRO {jcss} {"Journal of Computer and System Sciences"} + +MACRO {scp} {"Science of Computer Programming"} + +MACRO {sicomp} {"SIAM Journal on Computing"} + +MACRO {tocs} {"ACM Transactions on Computer Systems"} + +MACRO {tods} {"ACM Transactions on Database Systems"} + +MACRO {tog} {"ACM Transactions on Graphics"} + +MACRO {toms} {"ACM Transactions on Mathematical Software"} + +MACRO {toois} {"ACM Transactions on Office Information Systems"} + +MACRO {toplas} {"ACM Transactions on Programming Languages and Systems"} + +MACRO {tcs} {"Theoretical Computer Science"} + +READ + +EXECUTE {init.field.constants} + +FUNCTION {sortify} +{ purify$ + "l" change.case$ +} + +FUNCTION {sortify.names} +{ " \harvardand\ " " " replace.substring + " et~al." " zzz" replace.substring + sortify +} + +FUNCTION {author.key.label} +{ author empty$ + { key empty$ + { title.field 'field.used := } + { key.field 'field.used := } + if$ + } + { author.field 'field.used := } + if$ +} + +FUNCTION {author.editor.key.label} +{ author empty$ + { editor empty$ + { key empty$ + { title.field 'field.used := } + { key.field 'field.used := } + if$ + } + { editor.field 'field.used := } + if$ + } + { author.field 'field.used := } + if$ +} + +FUNCTION {author.key.organization.label} +{ author empty$ + { key empty$ + { organization empty$ + { title.field 'field.used := } + { organization.field 'field.used := } + if$ + } + { key.field 'field.used := } + if$ + } + { author.field 'field.used := } + if$ +} + +FUNCTION {editor.key.organization.label} +{ editor empty$ + { key empty$ + { organization empty$ + { title.field 'field.used := } + { organization.field 'field.used := } + if$ + } + { key.field 'field.used := } + if$ + } + { editor.field 'field.used := } + if$ +} + +FUNCTION {sort.format.title} +{ 't := + "A " #2 + "An " #3 + "The " #4 t chop.word + chop.word + chop.word + sortify + #1 global.max$ substring$ +} + +FUNCTION {calc.label} %%%XXX change +{ make.abbr.label + title.field field.used = + { sort.format.title } + { sortify.names } + if$ + year field.or.null purify$ #-1 #4 substring$ sortify + * + 'sort.label := +} + +FUNCTION {preliminaries} %%%XXX change +{ type$ "book" = + type$ "inbook" = + or + 'author.editor.key.label + { type$ "proceedings" = + 'editor.key.organization.label + { type$ "manual" = + 'author.key.organization.label + 'author.key.label + if$ + } + if$ + } + if$ + author.field field.used = %%%XXX change + { + author num.names$ #2 > + { #1 } + { #0 } + if$ + 'etal.required := + } + { + editor.field field.used = + { + editor num.names$ #2 > + { #1 } + { #0 } + if$ + } + { #0 } + if$ + 'etal.required := + } + if$ + #1 'etal.allowed := +} + +FUNCTION {first.presort} +{ calc.label + sort.label + title.field field.used = + { skip$ } + { " " + * + make.list.label sortify.names + * + " " + * + title field.or.null + sort.format.title + * + } + if$ + #1 entry.max$ substring$ + 'sort.key$ := +} + +ITERATE {preliminaries} + +ITERATE {first.presort} + +SORT + +STRINGS { last.sort.label next.extra last.full.label} + +INTEGERS { last.extra.num last.etal.allowed} + +FUNCTION {initialize.confusion} +{ #0 int.to.chr$ 'last.sort.label := + #0 int.to.chr$ 'last.full.label := + #1 'last.etal.allowed := +} + +FUNCTION {confusion.pass} +{ last.sort.label sort.label = + { last.etal.allowed + { last.full.label make.full.label sortify.names = + { skip$ } + { #0 'etal.allowed := + #0 'last.etal.allowed := + } + if$ + } + { #0 'etal.allowed := } + if$ + } + { sort.label 'last.sort.label := + make.full.label sortify.names 'last.full.label := + #1 'last.etal.allowed := + } + if$ +} + +EXECUTE {initialize.confusion} + +ITERATE {confusion.pass} + +EXECUTE {initialize.confusion} + +REVERSE {confusion.pass} + +FUNCTION {initialize.last.extra.num} +{ #0 int.to.chr$ 'last.sort.label := + "" 'next.extra := + #0 'last.extra.num := +} + +FUNCTION {forward.pass} +{ last.sort.label sort.label = + { last.extra.num #1 + 'last.extra.num := + last.extra.num int.to.chr$ 'extra.label := + } + { "a" chr.to.int$ 'last.extra.num := + "" 'extra.label := + sort.label 'last.sort.label := + } + if$ +} + +FUNCTION {reverse.pass} +{ next.extra "b" = + { "a" 'extra.label := } + 'skip$ + if$ + year empty$ + { "n.d." extra.label emphasize * 'list.year := } + { year extra.label emphasize * 'list.year := } + if$ + extra.label 'next.extra := +} + +ITERATE {first.presort} + +SORT + +EXECUTE {initialize.last.extra.num} + +ITERATE {forward.pass} + +REVERSE {reverse.pass} + +FUNCTION {second.presort} +{ make.list.label + title.field field.used = + { sort.format.title } + { sortify.names } + if$ + " " + * + list.year field.or.null sortify + * + " " + * + title.field field.used = + { skip$ } + { title field.or.null + sort.format.title + * + } + if$ + #1 entry.max$ substring$ + 'sort.key$ := +} + +ITERATE {second.presort} + +SORT + +FUNCTION {begin.bib} +{ preamble$ empty$ + 'skip$ + { preamble$ write$ newline$ } + if$ + "\begin{thebibliography}{xx}" write$ newline$ +} + +EXECUTE {begin.bib} + +EXECUTE {init.state.consts} + +ITERATE {call.type$} + +FUNCTION {end.bib} +{ newline$ + "\end{thebibliography}" write$ newline$ +} + +EXECUTE {end.bib} diff --git a/doc/cbdc-it/cbdc-it.bib b/doc/cbdc-it/cbdc-it.bib new file mode 100644 index 000000000..639bb0c45 --- /dev/null +++ b/doc/cbdc-it/cbdc-it.bib @@ -0,0 +1,561 @@ +%% To be used with modified bibliography style agsm-mod + hyperref + natbib + italian babel + +@article{Adrian, + author = {Adrian, Tobias and Mancini-Griffoli}, + year = {2019}, + title = {{The Rise of Digital Money}}, + journal = {IMF Fintech Note}, + volume = {19/01}, +} + +@article{Agarwal, + author = {Agarwal, Ruchir and Miles S. Kimball}, + year = {2019}, + title = {{Enabling Deep Negative Rates to Fight Recessions: A Guide}}, + journal = {IMF Working Paper}, + volume = {19/84}, +} + + +@article{Agur, + author = {Agur, Itai and Anil Ari and Giovanni Dell'Ariccia}, + year = {2019}, + title = {{Designing Central Bank Digital Currencies}}, + journal = {IMF Working Paper}, + volume = {19/252}, +} + +@article{Allen, + author = {Allen, Sarah and Srđjan Čapkun and Ittay Eyal and Giulia Fanti and Bryan A. Ford and James Grimmelmann and Ari Juels and Kari Kostiainen and Sarah Meiklejohn and Andrew Miller and Eswar Prasad and Karl Wüst and Fan Zhang}, + year = {2020}, + title = {{Design Choices for Central Bank Digital Currency: Policy and Technical Considerations}}, + journal = {NBER Working Paper}, + volume = {27634}, +} + +@article{Alves, + author = {Alves, Tiago and Don Felton}, + year = {2004}, + title = {TrustZone: Integrated hardware and software security}, + journal = {ARM IQ}, + volume = {3}, + number = {4}, + pages = {18--24}, +} + +@article{AuerBoehme, + author = {Auer, Raphael and Rainer Böhme}, + year = {2020}, + title = {The technology of retail central bank digital currency}, + journal = {BIS Quarterly Review}, + month = {March}, + pages = {85--96}, +} + +@article{AuerCornelli, + author = {Auer, Raphael and Giulio Cornelli and Jon Frost}, + year = {2020}, + title = {{Taking stock: ongoing retail CBDC projects}}, + journal = {BIS Quarterly Review}, + month = {March}, + pages = {97--98}, +} + +@booklet{BIS, + author = {{Bank for International Settlements}}, + year = {2018}, + title = {{Central Bank Digital Currencies. Joint Report of the Committee on Payments and Market Infrastructures and Markets Committee}}, +} + +@booklet{BoE, + author = {{Bank of England}}, + year = {2020}, + title = {{Central Bank Digital Currency: Opportunities, Challenges and Design. Discussion Paper}}, + month = {March}, +} + +@article{Baiocchi, + author = {Baiocchi, Giovanni and Walter Distaso}, + year = {2003}, + title = {{GRETL: Econometric Software for the GNU Generation}}, + journal = {Journal of Applied Econometrics}, + volume = {18}, + pages = {105-110}, +} + +@article{Bech, + author = {Bech, Morten and Rodney Garratt}, + year = {2017}, + title = {Central bank cryptocurrencies}, + journal = {BIS Quarterly Review}, + month = {September}, + pages = {55--70}, +} + +@article{Berentsen, + author = {Berentsen, Aleksander and Fabian Schär}, + year = {2018}, + title = {{The Case for Central Bank Electronic Money and the Non-case for Central Bank Cryptocurrencies}}, + journal = {Federal Reserve Bank of St. Louis Review}, + volume = {100}, + number = {2}, + pages = {97--106}, +} + +@article{Bernstein2020, + author = {Bernstein, Daniel J. and Tanja Lange}, + year = {2020}, + title = {{eBACS: ECRYPT Benchmarking of Cryptographic Systems}}, + url = {\url{https://bench.cr.yp.to}, consultato il 17 marzo 2020}, +} + +@article{Bernstein2012, + author = {Bernstein, Daniel J. and Niels Duif and Tanja Lange and Peter Schwabe and Bo-Yin Yang}, + year = {2012}, + title = {High-speed high-security signatures}, + journal = {Journal of Cryptographic Engineering}, + volume = {2}, + pages = {77--89}, +} + +@InCollection{Bindseil, + author = {Bindseil, Ulrich}, + year = {2020}, + title = {{Tiered CBDC and the financial system}}, + publisher = {European Central Bank}, + series = {ECB Working Paper}, + number = {2351}, + month = {January}, +} + +@article{Boar, + author = {Boar, Codruta and Henry Holden and Amber Wadsworth}, + year = {2020}, + title = {Impending arrival - a sequel to the survey on central bank digital currency}, + journal = {BIS Papers}, + volume = {107}, +} + +@article{Boneh, + author = {Boneh, Dan}, + year = {1999}, + title = {{Twenty Years of Attacks on the RSA Cryptosystem}}, + journal = {Notices of the AMS}, + volume = {42}, + number = {2}, + pages = {202--213}, +} + +@InCollection{Bordo, + author = {Bordo, Michael D. and Andrew T. Levin}, + year = {2017}, + title = {Central bank digital currency and the future of monetary policy}, + publisher = {National Bureau of Economic Research}, + series = {NBER Working Paper Series}, + number = {23711}, +} + +@article{Brunnermeier, + author = {Brunnermeier, Markus and Dirk Niepelt}, + year = {2019}, + title = {{On the Equivalence of Private and Public Money}}, + journal = {Journal of Monetary Economics}, + volume = {106}, + pages = {27--41}, +} + +@article{Buiter, + author = {Buiter, Willem H. and Nikolaos Panigirtzoglou}, + year = {2003}, + title = {{Overcoming the Zero Bound on Nominal Interest Rates with Negative Interest on Currency: Gesell's Solution}}, + journal = {The Economic Journal}, + volume = {113}, + number = {490}, + pages = {723--746}, +} + +@InCollection{Bullmann, + author = {Bullmann, Dirk and Jonas Klemm and Andrea Pinna}, + year = {2019}, + title = {In search for stability in crypto-assets: are stablecoins the solution?}, + publisher = {European Central Bank}, + series = {ECB Occasional Paper Series}, + number = {230}, +} + +@inproceedings{Camenisch2007, + author = {Camenisch, Jan and Aanna Lysyanskaya and Mira Meyerovich}, + year = {2007}, + title = {{Endorsed E-Cash}}, + booktitle = {\textit{2007 IEEE Symposium on Security and Privacy (SP'07)}}, + month = {May}, + pages = {101--115}, +} + +@inproceedings{Camenisch2005, + author = {Camenisch, Jan and Susan Hohenberger and Anna Lysyanskaya}, + year = {2005}, + title = {{Compact E-Cash}}, + booktitle = {\textit{Advances in Cryptology -- EUROCRYPT 2005: 24th Annual International Conference on the Theory and Applications of Cryptographic Techniques}}, + address = {Aarhus, Denmark}, + month = {May}, + day = {22-26}, + editor = {Ed. di Ronald Cramer}, + publisher = {Springer-Verlag Berlin Heidelberg}, +} + + + +@inproceedings{Canard, + author = {Canard, Sébastien and Aline Gouget}, + year = {2007}, + title = {Divisible e-cash systems can be truly anonymous}, + booktitle = {\textit{Annual International Conference on the Theory and Applications of Cryptographic Techniques}}, + pages = {482--497}, +} + +@misc{CCC, + author = {{CCC e.V.}}, + year = {2017}, + title = {{Chaos Computer Club hacks e-motor charging stations}}, + howpublished = {34c3}, +} + +@article{Chapman, + author = {Chapman, James and Rodney Garratt and Scott Hendry and Andrew McCormack and Wade McMahon}, + year = {2017}, + title = {{Project Jasper: Are Distributed Wholesale Payment Systems Feasible Yet?}}, + journal = {Financial System Review}, + publisher = {Bank of Canada}, + month = {June}, + pages = {59--69}, +} + +@inproceedings{Chaum1983, + author = {Chaum, David}, + year = {1983}, + title = {Blind signatures for untraceable payments}, + booktitle = {\textit{Advances in Cryptology: Proceedings of Crypto `82}}, + pages = {199--203}, +} + +@inproceedings{Chaum1990, + author = {Chaum, David and Amos Fiat and Moni Naor}, + year = {1990}, + title = {Untraceable electronic cash}, + booktitle = {\textit{Advances in Cryptology: Proceedings of CRYPTO '88}}, + pages = {319--327}, +} + +@inproceedings{Danezis, + author = {Danezis, George and Sarah Meiklejohn}, + year = {2016}, + title = {{Centrally Banked Cryptocurrencies}}, + booktitle = {\textit{23nd Annual Network and Distributed System Security Symposium, NDSS2016}}, + address = {San Diego, California, USA}, + month = {February}, + day = {21--24}, + publisher = {The Internet Society}, +} + +@article{Diffie, + author = {Diffie, Whitfield and Martin Hellmann}, + year = {1976}, + title = {{New Directions in Cryptography}}, + journal = {IEEE Trans. on Inf. Theory, IT-22}, + pages = {644--654}, +} + +@phdthesis{Dold, + author = {Dold, Florian}, + year = {2019}, + title = {{The GNU Taler System: Practical and Provably Secure Electronic Payments. PhD Thesis}}, + school = {University of Rennes 1}, +} + +@article{ECB, + author = {{European Central Bank}}, + year = {2019}, + title = {Exploring anonymity in central bank digital currencies}, + journal = {In Focus}, + number = {4}, + month = {December}, +} + +@inproceedings{Fuchsbauer, + author = {Fuchsbauer, Georg and David Pointcheval and Damien Vergnaud}, + year = {2009}, + title = {Transferable constant-size fair e-cash}, + booktitle = {International Conference on Cryptology and Network Security}, + publisher = {Springer-Verlag Berlin Heidelberg}, + pages = {226--247}, +} + +@inproceedings{Garcia, + author = {Garcia, Flavio and Gerhard de Koning Gans and Ruben Muijrers and Peter van Rossum and Roel Verdult and Ronny Wichers Schreur and Bart Jacobs}, + year = {2008}, + title = {{Dismantling MIFARE Classic}}, + booktitle = {\textit{European Symposium on Research in Computer Security}}, +} + +@article{Garratt, + author = {Garratt, Rod and Michael Lee and Brendan Malone and Antoine Martin}, + year = {2020}, + title = {{Token- or Account-Based? A Digital Currency Can Be Both}}, + journal = {Liberty Street Economics}, + publisher = {Federal Reserve Bank of New York}, + month = {August}, + day = {12}, +} + +@article{Goodfriend, + author = {Goodfriend, Marvin}, + year = {2000}, + title = {{Overcoming the Zero Bound on Interest Rate Policy}}, + journal = {Journal of Money, Credit, and Banking}, + volume = {32}, + number = {4}, + pages = {1007--1035}, +} + +@article{Johnston, + author = {Johnston, Casey}, + year = {2010}, + title = {PS3 hacked through poor cryptography implementation}, + journal = {Ars Technica}, + month = {December}, + day = {30}, +} + +@Misc{Jordan, + note = {Discorso in occasione del 30º anniversario del Centro di scienze economiche (WWZ) e dell’Associazione degli economisti basilesi (VBÖ)}, + author = {Jordan, Thomas J.}, + year = {2019}, + title = {Valute, moneta e token digitali}, + publisher = {University of Basel}, + month = {September}, + howpublished = {\url{https://www.snb.ch/it/mmr/speeches/id/ref_20190905_tjn/source/ref_20190905_tjn.it.pdf}}, +} + +@article{Kahn2009, + author = {Kahn, Charles M. and William Roberds}, + year = {2009}, + title = {{Why Pay? An Introduction to Payments Economics}}, + journal = {Journal of Financial Intermediation}, + number = {18}, + pages = {1--23}, +} + +@article{Kahn2005, + author = {Kahn, Charles M. and James McAndrews and William Roberds}, + year = {2005}, + title = {{Money is Privacy}}, + journal = {International Economic Review}, + volume = {46}, + number = {2}, + pages = {377--399}, +} + +@article{Kasper, + author = {Kasper, Timo and Michael Silbermann and Christof Paar}, + year = {2010}, + title = {All you can eat or breaking a real-world contactless payment system}, + journal = {Financial Cryptography and Data Security, Lecture Notes in Computer Science}, + volume = {6052}, + pages = {343--50}, +} + +@inproceedings{Katzenbeisser, + author = {Katzenbeisser, Stefan and Ünal Kocabaş and Vladimir Rožić and Ahmad-Reza Sadeghi and Ingrid Verbauwhede and Christian Wachsmann}, + year = {2012}, + title = {{PUFs: Myth, Fact or Busted? A Security Evaluation of Physically Unclonable Functions (PUFs) Cast in Silicon}}, + booktitle = {\textit{Cryptographic Hardware and Embedded Systems -- CHES 2012. Lecture Notes in Computer Science}}, + volume = {7428}, + pages = {283--301}, +} + +@book{Keynes, + author = {Keynes, John Maynard}, + year = {1936}, + title = {The General Theory of Employment, Interest and Money}, + publisher = {Macmillan}, +} + +@article{Kiff, + author = {Kiff, John and Jihad Alwazir and Sonja Davidovic and Aquiles Farias and Ashraf Khan and Tanai Khiaonarong and Majid Malaika and Hunter Monroe and Nobu Sugimoto and Hervé Tourpe and Peter Zhou}, + year = {2020}, + title = {{A Survey of Research on Retail Central Bank Digital Currency}}, + journal = {IMF Working Paper}, + volume = {20/104}, +} + +@InCollection{Kumhof, + author = {Kumhof, Michael and Clare Noone}, + year = {2018}, + title = {Central bank digital currencies - design principles and balance sheet implications}, + publisher = {Bank of England}, + series = {Staff Working Paper}, + number = {725}, +} + +@inproceedings{Lapid, + author = {Lapid, Ben and Avishai Wool}, + year = {2018}, + title = {{Cache-Attacks on the ARM TrustZone Implementations of AES-256 and AES-256-GCM via GPU-Based Analysis}}, + booktitle = {\textit{International Conference on Selected Areas in Cryptography. Lecture Notes in Computer Science}}, + volume = {11349}, +} + +@article{Lerner, + author = {Lerner, Josh and Jean Tirole}, + year = {2005}, + title = {{The Scope of Open Source Licensing}}, + journal = {Journal of Law, Economics \& Organization}, + volume = {21}, + pages = {20-56}, +} + +@misc{Libra, + author = {{Libra Association}}, + year = {2020}, + title = {{Libra White Paper v2.0}}, + url = {\url{https://libra.org/en-US/white-paper}}, +} + +@inproceedings{Lim, + author = {Lim, Chae Hoon and Phil Joong Lee}, + year = {1997}, + title = {A key recovery attack on discrete log-based schemes using a prime order subgroup}, + booktitle = {\textit{CRYPTO 1997. Lecture Notes in Computer Science}}, + volume = {1294}, +} + +@InCollection{Lyons, + author = {Lyons, Richard K. and Ganesh Viswanath-Natraj}, + year = {2020}, + title = {{What Keeps Stablecoins Stable?}}, + publisher = {National Bureau of Economic Research}, + series = {NBER Working Paper Series}, + number = {27136}, + month = {May}, +} + +@article{Mancini-Griffoli, + author = {Mancini-Griffoli and Maria Soledad Martinez Peria and Itai Agur and Anil Ari and John Kiff and Adina Popescu and Celine Rochon}, + year = {2018}, + title = {{Casting Light on Central Bank Digital Currency}}, + journal = {IMF Staff Discussion Notes}, + volume = {18/08}, + publisher = {International Monetary Fund}, +} + +@misc{Nakamoto, + author = {Nakamoto, Satoshi}, + year = {2008}, + title = {{Bitcoin: A Peer-to-Peer Electronic Cash System}}, + url = {\url{https://www.bitcoin.com/bitcoin.pdf}}, +} + +@book{Narayanan, + author = {Narayanan, Arvind and Joseph Bonneau and Edward Felten and Andrew Miller and Steven Goldfeder}, + year = {2016}, + title = {Bitcoin and Cryptocurrency Technologies: A Comprehensive Introduction}, + publisher = {Princeton University Press}, +} + +@misc{Niepelt, + author = {Niepelt, Dirk}, + year = {2020}, + title = {Digital money and central bank digital currency: An executive summary for policymakers}, + howpublished = {\url{https://voxeu.org/article/digital-money-and-central-bank-digital-currency-executive-summary}}, +} + +@inproceedings{Okamoto, + author = {Okamoto, Tatsuaki}, + year = {1995}, + title = {{An Efficient Divisible Electronic Cash Scheme}}, + booktitle = {\textit{Advances in Cryptology --- CRYPT0'95: 15th Annual International Cryptology Conference Santa Barbara, California, USA, 27--31 agosto, 1995 Proceedings}}, + editor = {Ed. di Don Coppersmith}, + publisher = {Springer-Verlag Berlin Heidelberg}, + pages = {438--451}, +} + +@article{Pinto, + author = {Pinto, S. and N. Santos}, + year = {2019}, + title = {{Demystifying ARM TrustZone: A Comprehensive Survey}}, + journal = {ACM Computing Surveys}, + volume = {51}, + number = {6}, + month = {January}, + pages = {1--31} +} + +@article{Rivest, + author = {Rivest, Ronald L. and Adi Shamir and Leonard Adleman}, + year = {1978}, + title = {{A Method for Obtaining Digital Signatures and Public Key Cryptosystems}}, + journal = {Comm. ACM}, + volume = {21}, + number = {2}, +} + +@book{Solove, + author = {Solove, Daniel J.}, + year = {2011}, + title = {Nothing to Hide: The false tradeoff between privacy and security}, + publisher = {New Haven \& London: Yale University Press}, +} + +@article{Soukup, + author = {Soukup, Michael and Bruno Muff}, + year = {2007}, + title = {{Die Postcard lässt sich fälschen}}, + journal = {Sonntagszeitung}, + month = {April}, + day = {22}, +} + +@article{Stallman, + author = {Stallman, Richard}, + year = {1985}, + title = {{The GNU manifesto}}, + journal = {Dr. Dobb's Journal of Software Tools}, + volume = {10}, + number = {3}, + pages = {30--35}, +} + +@TechReport{Riksbank, + author = {{Sveriges Riksbank}}, + year = {2020}, + title = {{The Riksbank's e-krona project}}, + month = {February}, + institution = {Sveriges Riksbank}, + url = {\url{https://www.riksbank.se/globalassets/media/rapporter/e-krona/2019/the-riksbanks-e-krona-pilot.pdf}}, +} + +@misc{Wojtczuk, + author = {Wojtczuk, Rafal and Joanna Rutkowska}, + year = {2009}, + title = {{Attacking Intel Trusted Execution Technology}}, + howpublished = {BlackHat-DC 2009}, +} + +@article{Yalta2010, + author = {Yalta, A. Talha and A. Yasemin Yalta}, + year = {2010}, + title = {{Should Economists Use Open Source Software for Doing Research?}}, + journal = {Computational Economics}, + volume = {35}, + pages = {371--394}, +} + +@article{Yalta2008, + author = {Yalta, A. Talha and Riccardo Lucchetti}, + year = {2008}, + title = {{The GNU/Linux Platform and Freedom Respecting Software for Economists}}, + journal = {Journal of Applied Econometrics}, + volume = {23}, + pages = {279-286}, +} diff --git a/doc/cbdc-it/cbdc-it.tex b/doc/cbdc-it/cbdc-it.tex new file mode 100644 index 000000000..0159b153d --- /dev/null +++ b/doc/cbdc-it/cbdc-it.tex @@ -0,0 +1,1303 @@ +\documentclass[a4paper]{article} +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage[top=2cm,bottom=2cm]{geometry} +\usepackage{url} +\usepackage{amsmath} +\usepackage{hyperref} +\usepackage{graphicx} +\usepackage{natbib} +\usepackage[italian]{babel} +\title{Come una banca centrale dovrebbe emettere una moneta digitale} +\author{David Chaum\footnote{david@chaum.com} \\ + xx Network \and + Christian Grothoff\footnote{christian.grothoff@bfh.ch} \\ + BFH\footnote{Università di Scienze Applicate di Berna} + \ e Progetto GNU \and + Thomas Moser\footnote{thomas.moser@snb.ch} \\ + Banca Nazionale Svizzera} +\date{Questa versione: febbraio 2022 \\ + Prima versione: maggio 2020} + +\setlength\parskip{5pt plus 1pt} % More space between paragraphs +\addto\captionsitalian{\renewcommand{\figurename}{Diagramma}} +\AtBeginDocument{\renewcommand{\harvardand}{\&}} +\hyphenation{CBDC} + +\begin{document} + +\maketitle + +\begin{abstract} +Con l'emergere di Bitcoin e delle criptovalute stabili (per es. Diem, +già nota come Libra) recentemente proposte dai colossi del web, le +banche centrali affrontano una crescente concorrenza da parte di +operatori privati che offrono la propria alternativa digitale al +contante fisico. Non trattiamo qui la questione normativa se una banca +centrale debba emettere o meno una moneta digitale. Contribuiamo invece +all'attuale dibattito di ricerca spiegando in che modo una banca centrale +potrebbe farlo, se lo volesse. Proponiamo un sistema basato su token +senza tecnologia di registro distribuito, e mostriamo che le monete +elettroniche emesse in passato, basate solo su software, possono essere +migliorate per tutelare la privacy nelle transazioni, soddisfare i +requisiti normativi in modo efficace e offrire un livello di protezione +resistente ai computer quantistici contro il rischio sistemico per +la privacy. Né la politica monetaria né la stabilità del sistema +finanziario sarebbero realmente interessate da questo sistema dal +momento che una moneta emessa in questo modo replicherebbe il contante +fisico anziché i depositi bancari. \\ + +JEL: E42, E51, E52, E58, G2 +\\ + +Parole chiave: monete digitali, banca centrale, CBDC, firma cieca, +criptovalute stabili, \textit{stablecoins} +\end{abstract} + +\vspace{40pt} + +\section*{Ringraziamenti} +Vorremmo ringraziare Michael Barczay, Roman Baumann, Morten Bech, +Nicolas Cuche, Florian Dold, Andreas Fuster, Stefan Kügel, Benjamin +Müller, Dirk Niepelt, Oliver Sigrist, Richard Stallman, Andreas Wehrli +e tre collaboratori anonimi per i loro commenti e suggerimenti. Le +posizioni, le opinioni, i risultati e le conclusioni o raccomandazioni +espresse in questo documento sono strettamente quelle degli autori. +Non riflettono necessariamente le posizioni della Banca nazionale +svizzera (BNS). La BNS declina ogni responsabilità per eventuali +errori, omissioni o inesattezze che dovessero comparire nel documento. + +Traduzione: Dora Scilipoti, con contributi da Luca Saiu +\newpage + +%\tableofcontents + +%\bibpunct{(}{)}{ e }{a}{}{,} + +\section{Introduzione}\label{1.-introduzione} + +Dall'avvento dei personal computer negli anni ottanta, e più +specificamente da quando nel 1991 la \textit{National Science +Foundation} revocò le restrizioni sull'uso di Internet per scopi +commerciali, c'è stata una ricerca sulla creazione di moneta digitale +per i pagamenti online. La prima proposta è stata quella +di~\cite{Chaum1983}. Sebbene tali metodi siano stati attuati, non hanno +preso piede; le carte di credito sono invece diventate il metodo più +diffuso per i pagamenti online. La proposta di~\cite{Nakamoto} per una +versione puramente \textit{peer-to-peer} di moneta digitale e il +conseguente lancio di Bitcoin avvenuto con successo hanno inaugurato +una nuova era di ricerca e sviluppo di valute digitali. La piattaforma +CoinMarketCap elenca oltre 5.000 criptovalute. Recentemente le banche +centrali hanno iniziato a considerare, o almeno a studiare, +l'emissione di monete digitali~\cite[vedi][]{AuerBoehme,AuerCornelli,Boar,Kiff,Mancini-Griffoli}. + +Attualmente le banche centrali emettono due tipi di moneta: (i) +riserve sotto forma di conti di regolamento presso le banche centrali, +destinate solo agli operatori dei mercati finanziari, e (ii) divisa +disponibile per tutti sotto forma di banconote. Di conseguenza, la +letteratura sulla moneta digitale di banca centrale (\textit{Central Bank +Digital Currency} - CBDC) distingue tra (a) CBDC all'ingrosso ad +accesso ristretto e (b) CBDC al dettaglio disponibile per il +pubblico~\cite[si veda, ad esempio,][]{Bech}. +Una CBDC all'ingrosso sarebbe meno destabilizzante per il sistema attuale +dato che le banche e gli operatori dei mercati finanziari hanno già +accesso alla moneta digitale della banca centrale sotto forma di conti +presso questa istituzione, che utilizzano per regolare i pagamenti +interbancari. La domanda qui è se la tokenizzazione della moneta di banca +centrale e la tecnologia di registro distribuito (\textit{Distributed Ledger +Technology} - DLT) offrano vantaggi particolari rispetto ai sistemi con +regolamento lordo in tempo reale (\textit{Real-Time Gross Settlement} - RTGS) +esistenti. Finora la risposta è negativa, almeno per i pagamenti +interbancari nazionali~\cite[vedi][]{Chapman}. + +Una CBDC al dettaglio, che sarebbe una nuova forma di moneta di banca +centrale disponibile per il pubblico, potrebbe essere più destabilizzante +per il sistema attuale, a seconda di come è progettata. Più una CBDC +compete con i depositi delle banche commerciali, maggiore è la minaccia +ai finanziamenti bancari, con effetti potenzialmente negativi sul credito +bancario e sull'attività economica~\cite[vedi][]{Agur}. Tuttavia, una +CBDC al dettaglio potrebbe anche essere +vantaggiosa~\cite[vedi][]{Bordo,Berentsen,Bindseil,Niepelt,Riksbank,BoE}. +Mettere a disposizione di tutti una moneta elettronica di banca centrale +esente dal rischio di controparte potrebbe migliorare la stabilità e la +resilienza del sistema di pagamenti al dettaglio. Potrebbe inoltre fornire +un'infrastruttura di pagamento neutrale per incoraggiare la concorrenza, +l'efficienza e l'innovazione. Nel complesso, è probabile che i costi e i +benefici di una CBDC al dettaglio differiscano da un paese all'altro. Per +il punto di vista della Banca nazionale svizzera, che non ha in programma +l'emissione di una CBDC al dettaglio, si veda~\cite{Jordan}. + +Nel presente documento analizziamo la CBDC al dettaglio, ma senza +affrontare la questione se una banca centrale \emph{debba o meno} emetterla. +Ci concentriamo invece sul possibile design di una CBCD. L'interesse +per la progettazione di CBDC è recentemente aumentato +considerevolmente~\cite[si veda, ad esempio,][]{Allen,BoE}. Il design che +proponiamo differisce notevolmente da altre proposte. Il nostro sistema +si basa sulla tecnologia eCash descritta da~\cite{Chaum1983} e \cite{Chaum1990}, +migliorandola. In particolare, proponiamo una CBDC basata su token, solo +con software e senza tecnologia di registro distribuito. La DLT è +un'architettura interessante in assenza di un operatore centrale o se le +entità che interagiscono non accettano di nominare un operatore centrale +fidato. Questo non è certo il caso di una CBDC al dettaglio emessa da una +\emph{banca centrale}. Distribuire il registro delle transazioni della +banca centrale con una \textit{blockchain} non fa che aumentare i costi +di transazione; non porta alcun vantaggio tangibile nell'implementazione +da parte di una banca centrale. L'utilizzo della DLT per emettere moneta +digitale può essere utile in assenza di una banca centrale (ad esempio, +il progetto Sovereign delle Isole Marshall) o se l'intenzione esplicita +è quella di fare a meno di una banca centrale (ad esempio, +Bitcoin).\footnote{Potrebbero esserci casi opportuni di utilizzo della +DLT per le infrastrutture dei mercati finanziari, come gli scambi digitali, +dove sorge la questione di come incorporare la moneta della banca centrale +all'interno di una struttura DLT per eseguire i regolamenti. Tuttavia, +in tali situazioni i potenziali benefici della DLT, ad esempio costi +inferiori o riconciliazione automatica, non derivano da un'emissione +decentralizzata di moneta di banca centrale.} + +La CBDC basata su token che proponiamo consente anche di preservare +una caratteristica fondamentale del contante fisico: la privacy nelle +transazioni. Spesso si sostiene che l'uso della crittografia per la +tutela della privacy richieda così tanta potenza di calcolo da rendere +impraticabile la sua implementazione su dispositivi +portatili~\cite[vedi][]{Allen}. Sebbene questo possa essere vero nel +caso di una tecnologia di registro distribuito, dove la tracciabilità +delle transazioni è necessaria per prevenire la doppia spesa~\cite[][]{Narayanan}, +non lo è nel caso proposto in questo documento, dove si ha un protocollo +di firma cieca di tipo Chaum e la partecipazione di una banca centrale. +La nostra CBDC, basata su firme cieche e un'architettura a due livelli, +garantisce una tutela della privacy nelle transazioni perfetta e +quanto-resistente, fornendo al contempo protezioni sociali che sono di +fatto più potenti rispetto a quelle delle banconote per la lotta al +riciclaggio di denaro (\textit{Anti-Money Laundering} - AML) e al +finanziamento del terrorismo (\textit{Counter Terrorism Financing} - CFT). + +La privacy nelle transazioni è importante per tre motivi. In primo luogo, +protegge gli utenti dal potenziale abuso di monitoraggio e sorveglianza +da parte dei governi. Anche se si pensa di non avere nulla da nascondere, +i piani di sorveglianza di massa restano problematici, se non altro per +il rischio di errori e abusi, soprattutto se condotti senza trasparenza +e responsabilità~\cite[vedi][]{Solove}. In secondo luogo, la privacy nelle +transazioni protegge gli utenti dallo sfruttamento dei dati da parte dei +fornitori di servizi di pagamento. Infine, salvaguarda gli utenti dalla +controparte nelle transazioni in quanto esclude possibili comportamenti +opportunistici successivi o rischi per la sicurezza dovuti a negligenza +o mancata protezione dei dati dei clienti~\cite[vedi][]{Kahn2005}. + +Questo documento è strutturato come segue: nella Sezione II si spiega +la differenza tra la moneta di banca centrale e altri tipi di moneta. +Nella Sezione III si esaminano i modelli di CBDC tipici e generici prima +di proporre il nostro progetto nella Sezione IV. Si considerano poi +gli aspetti normativi e le politiche (V) e il relativo lavoro (VI). +Infine, si conclude (VII). + + +\section{Cos'è la moneta di banca centrale?} + \label{2.-cos'è-la-moneta-di-banca-centrale} + +La moneta è un attivo che può essere utilizzato per acquistare beni e +servizi. Per essere considerato moneta, l'attivo deve essere accettato +da entità diverse dall'emittente. Ecco perché i voucher, ad esempio, +non sono considerati moneta. La moneta autentica deve essere +\emph{comunemente} accettata come mezzo di scambio. Sebbene la moneta +abbia altre funzioni, ad esempio come unità di conto e riserva di valore, +la sua caratteristica distintiva è la sua funzione di mezzo di scambio. +Normalmente l'unità di conto (cioè come avvengono la fissazione dei +prezzi e la contabilizzazione dei debiti) coincide per ragioni +pratiche con il mezzo di scambio. Una separazione può tuttavia +verificarsi se il valore del mezzo di scambio manca di stabilità +rispetto ai beni e servizi scambiati.\footnote{Ciò può accadere +spontaneamente in un ambito caratterizzato da un'inflazione elevata, +ad esempio quando i prezzi sono quotati in USD ma i pagamenti vengono +effettuati in valuta locale. Lo stesso vale per i pagamenti in Bitcoin, +dove i prezzi sono solitamente fissati in USD o altre valute locali a +causa dell'elevata volatilità del Bitcoin. Una separazione può anche +essere progettata appositamente, come nel caso +dell'\textit{Unidad de Fomento} (UF) in Cile o i Diritti Speciali di +Prelievo (DSP) del Fondo Monetario Internazionale (FMI). Tuttavia, +anche in questi casi lo scopo è quello di avere un'unità di conto più +stabile.} La moneta deve anche essere una riserva di valore per fungere +da mezzo di scambio perché deve preservare il suo potere d'acquisto tra +il momento in cui si riceve e quello in cui si spende. In ogni modo, +ci sono molti altri attivi che fungono da riserva di valore, come azioni, +obbligazioni, metalli preziosi e immobili. Pertanto, la caratteristica +di riserva di valore non è distintiva della moneta. + +In un'economia moderna, il pubblico utilizza due tipi diversi di +moneta: (a) moneta statale e (b) moneta privata. La moneta statale viene +generalmente emessa dalla banca centrale, che agisce in qualità di +agente dello Stato. La moneta della banca centrale è disponibile per +alcune istituzioni finanziarie sotto forma di depositi presso la banca +centrale (riserve) e per il pubblico sotto forma di valuta (banconote e +monete), nota anche come «contante». In una economia moderna con valuta +fiat, tale moneta non ha un valore intrinseco. Legalmente è una passività +della banca centrale, sebbene non sia rimborsabile. Nella maggior parte +dei paesi, la moneta della banca centrale è definita come avente corso +legale, il che significa che deve essere accettata per il pagamento dei +debiti monetari, comprese le tasse e le sanzioni legali. Sebbene ciò +garantisca un certo valore alla moneta della banca centrale, lo status +di corso legale non è sufficiente per mantenere un valore stabile. È la +politica monetaria della banca centrale che mantiene il valore della +moneta. Mantenere la stabilità dei prezzi, vale a dire un valore stabile +della moneta rispetto a quello dei beni e dei servizi scambiati, è +infatti una delle principali responsabilità delle banche centrali. + +La maggior parte dei pagamenti in un'economia moderna vengono effettuati +con moneta privata emessa dalle banche commerciali ed è costituita da +depositi bancari a vista che le persone detengono presso queste banche. +Sono depositi che si posssono utilizzare mediante assegni, carte di +debito, carte di credito e altri mezzi di trasferimento di denaro e +costituiscono una passività della banca commerciale di riferimento. Una +caratteristica fondamentale di questi depositi è che le banche commerciali +garantiscono la convertibilità su richiesta in moneta della banca centrale +ad un prezzo fisso, vale a dire, alla pari. I depositanti possono prelevare +i propri fondi in contante o trasferirli ad un valore fisso di 1:1. Le +banche commerciali mantengono stabile il valore della propria moneta +ancorandola a quella della banca centrale. + +Tuttavia, in un sistema di riserva frazionaria, una banca commerciale, +anche se solvibile, potrebbe non avere liquidità a sufficienza per +onorare la sua promessa di convertire i depositi bancari in moneta +della banca centrale (ad esempio, nel caso di una corsa agli sportelli) +in modo tale che i clienti non possano prelevare i propri soldi. Una +banca può anche diventare insolvente e fallire, e di conseguenza i +clienti possono perdere denaro. Per questo motivo le banche commerciali +sono soggette a regolamentazioni volte a mitigare tali rischi. + +Una differenza notevole tra la moneta di una banca centrale e la +moneta privata emessa da una banca commerciale è, pertanto, che +quest'ultima comporta un rischio di controparte. Una banca centrale +può sempre adempiere ai suoi obblighi utilizzando la propria moneta +non rimborsabile. In un'economia nazionale, la moneta della banca +centrale è l'unico attivo monetario esento da rischi di credito e di +liquidità. È pertanto l'attivo tipicamente preferito per regolare i +pagamenti nelle infrastrutture dei mercati finanziari (si veda, per +esempio, \textit{CPMI-IOSCO Principles for Financial Market +Infrastructures}, 2012). Un'altra differenza risiede nella capacità +della moneta della banca centrale di sostenere il sistema monetario +nazionale fornendo un valore di riferimento con cui la moneta delle +banche commerciali mantiene la piena convertibilità. + +A parte le banche commerciali, altre entità private tentano +occasionalmente di emettere moneta; le criptovalute sono solo il +tentativo più recente. Ma a differenza dei depositi bancari, tale +moneta non è comunemente accettata come mezzo di scambio. Questo vale +anche per Bitcoin, la criptovaluta più ampiamente accettata. Un +ostacolo all'utilità delle criptovalute come mezzo di scambio è l'elevata +volatilità del loro valore. In risposta a questo problema sono emerse +le criptovalute stabili, cosiddette «stablecoins». Le +\textit{stablecoin} generalmente tentano di stabilizzare il proprio +valore in due modi: imitando le banche centrali (\textit{stablecoin} +algoritmiche) o imitando le banche commerciali e strumenti di +investimento (\textit{stablecoin} ancorate ad attivi).\footnote{Per una +tassonomia delle \textit{stablecoin}, si veda~\cite{Bullmann}.} + +Le «\textit{stablecoin} algoritmiche» si basano su algoritmi per regolare +l'offerta della moneta. In altre parole, cercano di stabilizzarne il +prezzo attraverso una «politica monetaria algoritmica». Esistono +esempi di tali \textit{stablecoin} (per esempio, Nubits), ma finora nessuna è +riuscita a stabilizzare il proprio valore per molto tempo. + +Le \textit{stablecoin} «ancorate ad attivi» differiscono in base al tipo +di attivo che utilizzano e ai diritti concessi ai possessori. I tipi di +attivi generalmente utilizzati sono: valuta (riserve di banche centrali, +banconote o depositi presso banche commerciali), materie prime (come +l'oro), titoli e talvolta altre criptovalute. La capacità di un tale +schema di stabilizzare il valore della moneta rispetto agli attivi +sottostanti dipende in modo cruciale dai diritti legali acquisiti dai +detentori della moneta. Se una \textit{stablecoin} è riscattabile ad un +prezzo fisso (per es. 1 moneta = 1 USD \\ o 1 moneta = 1 oncia d'oro), +la stabilità si può teoricamente ottenere.\footnote{Se possa stabilizzare +il valore della \textit{stablecoin} anche rispetto ai beni e servizi +scambiati dipende essenzialmente da quanto sia stabile il valore degli +attivi su cui poggia rispetto al valore dei beni e servizi.} Tale strategia +riproduce essenzialmente quella delle banche commerciali garantendo la +convertibilità nell'attivo sottostante su richiesta. Tuttavia, a differenza +dei depositi bancari, che in genere sono coperti solo parzialmente dalle +riserve della banca centrale, le \textit{stablecoin} sono spesso +completamente garantite dalle riserve di attivi sottostanti al fine di +evitare il rischio di liquidità, principalmente perché non dispongono di +tutele pubbliche tali come l'assicurazione dei depositi e il prestatore +di ultima istanza che offrono invece le banche regolamentate. + +Le \textit{stablecoin} che utilizzano le valute come attivi sono anche +dette «stablecoin a valuta fiat». Detenere il 100\% delle +garanzie sotto forma di valuta (banconote o depositi bancari) non risulta però +molto redditizio. Di conseguenza, i fornitori di \textit{stablecoin} hanno +un buon motivo per rispiarmiare sugli attivi passando ad un sistema di +riserva frazionaria, proprio come hanno fatto le banche +commerciali.\footnote{L'incertezza sulla garanzia delle +\textit{stablecoin} può essere uno dei motivi per cui vengono scambiate +al di sotto del loro valore nel mercato parallelo~\cite[vedi][]{Lyons}. +Casi simili si sono storicamente verificati anche con le banconote, quando +erano ancora emesse dalle banche commerciali. Le banconote venivano +scambiate a prezzi scontati nel mercato parallelo prima che l'emissione +fosse nazionalizzata e trasferita alle banche centrali come monopolio.} +Ciò comporta la riduzione degli attivi meno redditizi al minimo ritenuto +necessario per soddisfare il requisito di convertibilità e l'aumento +degli attivi liquidi a rendimento più elevato come i titoli di stato. +Questo migliora la redditività ma aumenta nel contempo il livello +di rischio. Tuttavia, anche se una \textit{stablecoin} fosse garantita +interamente da depositi presso le banche commerciali, rimarrebbe comunque +vulnerabile ai rischi di insolvenza del credito e di liquidità della +relativa banca. Tale rischio può essere evitato effettuando i depositi +presso la banca centrale in modo che siano le riserve di quest'ultima a +garantire la \textit{stablecoin}. Tali \textit{stablecoin} sono state +chiamate «CBDC sintetiche»~\cite[][]{Adrian}. È importante sottolineare che +queste \textit{stablecoin} non sono moneta di banca centrale e quindi +non costituiscono una CBDC in quanto non sono registrate come passività +della banca centrale e, pertanto, rimangono soggette al rischio di +controparte, ovvero al rischio di fallimento dell'emittente. + +Se una \textit{stablecoin} non è rimborsabile ad un prezzo fisso, la sua +stabilità rispetto all'attivo sottostante non è garantita. Se la +\textit{stablecoin} rappresenta comunque una quota di proprietà +dell'attivo sottostante, lo schema ricorda quello di un fondo comune di +investimento chiuso o di un fondo indicizzato quotato (\textit{Exchange-Traded +Fund} - ETF) e si applicano i relativi rischi. Il valore +della moneta dipenderà dal valore patrimoniale netto del fondo, ma il +suo valore effettivo può variare. Se ci sono partecipanti autorizzati +a creare e riscattare \textit{stablecoin} e quindi ad agire come +arbitraggisti, come nel caso degli ETF e come previsto per la +Diem~\cite[][]{Libra}, la deviazione si presume minima. + +Nel complesso, le \textit{stablecoin} hanno maggiori possibilità di +diventare moneta rispetto alle criptovalute, soprattutto se +adeguatamente regolamentate, anche se la disponibilità di CBDC +limiterebbe notevolmente la loro utilità. + +\section{Modelli generici di CBDC} \label{3.-modelli-generici-di-cbdc} + +Come abbiamo visto, la CBDC sarebbe una passività della banca +centrale. Due modelli possibili che si trovano nella letteratura +sull'argomento sono (a) CBDC basata su conti e (b) CBDC basata su +token (o sul valore). Questi modelli corrispondono ai due tipi +esistenti di moneta delle banche centrali e ai relativi sistemi di +pagamento~\cite[][]{Kahn2009}: riserve delle banche centrali +(sistema basato su conti) e banconote (sistema basato su token). Un +pagamento si verifica quando un'attivo monetario viene trasferito da un +pagatore a un beneficiario. In un sistema basato su conti, il +trasferimento avviene addebitando sul conto del pagatore e +accreditando sul conto del beneficiario. In un sistema basato su +token, il trasferimento avviene trasferendo il valore stesso o il +token, ovvero un oggetto che rappresenta l'attivo monetario. Il miglior +esempio di token è il contante (monete o banconote). Pagare in contanti +equivale a consegnare una moneta o una banconota. Non è necessario +registrare il trasferimento, il semplice possesso del token è +sufficiente. Pertanto, le parti non sono tenute a rivelare la propria +identità in nessun momento durante la transazione, entrambe possono +rimanere anonime. Ciononostante, il beneficiario deve essere in grado di +verificare l'autenticità del token. Questo è il motivo per cui le +banche centrali investono notevoli risorse nelle caratteristiche di +sicurezza delle banconote. + +È stato suggerito che la distinzione tra sistemi basati su conti e +quelli basati su token non sia applicabile alle monete digitali~\cite[][]{Garratt}. +Noi al contrario riteniamo che ci sia una differenza significativa. La +differenza essenziale risiede nelle informazioni contenute nell'attivo. +In un sistema basato su conti, gli attivi (i conti) sono riconducìbili +ad una cronologia delle transazioni che include tutte le operazioni di +credito e addebito dei conti. In un sistema basato su token, gli attivi +(i token) contengono solo informazioni sul valore del token e +sull'entità che lo ha emesso. I sistemi basati su token sono quindi +l'unica possibilità per ottenere la stessa privacy nelle transazioni che +offre il contante.\footnote{Sebbene il termine «Bitcoin» suggerisca +l'uso di token, Bitcoin è un sistema basato su conti. L'unica differenza +tra un sistema tradizionale basato su conti e una \textit{blockchain} è +che i conti non sono conservati in un database centrale ma in un +database decentralizzato di solo accodamento.} + +\subsection{CBDC basata su conti}\label{cbdc-basata-su-conti} + +Il modo più semplice per avviare una CBDC sarebbe consentire al +pubblico di detenere conti deposito presso la banca centrale. Ciò +comporta che la banca centrale si facesse responsabile dei controlli per +conoscere i propri clienti (\textit{Know-Your-Customer} - KYC) e di +garantire la conformità con i requisiti per la lotta al riciclaggio di +denaro e al finanziamento del terrorismo. Ciò includerebbe non solo la +gestione del processo iniziale di conoscenza del cliente, ma anche +l'autenticazione dei clienti per le transazioni bancarie, la gestione +delle frodi e delle autenticazioni false positive e false negative. +Data la scarsa presenza fisica delle banche centrali nella società e il +fatto che probabilmente oggi non siano disposte ad eseguire l'autenticazione +dei cittadini su larga scala, qualsiasi CBDC basata su conti richiederebbe +alla banca centrale di delegare questi compiti. Tutti i servizi di +assistenza e manutenzione di tali conti potrebbero essere affidati ad +operatori esterni~\cite[][]{Bindseil}, oppure le banche commerciali potrebbero +essere obbligate per legge ad aprire conti presso la banca centrale per i +propri clienti~\cite[][]{Berentsen}. + +Una CBDC basata su conti darebbe potenzialmente alla banca centrale +l'accesso a molti dati aggiuntivi. Uno dei motivi di preoccupazione è +che i governi potrebbero facilmente mettere in atto una sorveglianza +di massa e imporre sanzioni ai singoli titolari dei conti. La natura +centralizzata di tali interventi li rende poco costosi e facili da +applicare nei confronti di persone o gruppi. Ci sono molti esempi di +sorveglianza abusiva contro critici e oppositori politici, anche nelle +democrazie. Si potrebbe argomentare che le banche centrali indipendenti +siano in grado di salvaguardare tali informazioni dall'intrusione del +governo e dagli abusi politici, ma ciò aprirebbe comunque una nuova +strada alle pressioni politiche che minacciano l'indipendenza delle +banche centrali. Inoltre, un database centrale sarebbe un obiettivo +cospicuo per gli attacchi: anche l'accesso in sola lettura ad una parte +del database potrebbe creare rischi significativi per le persone i cui +dati sarebbero esposti. + +Se dovessero fornire conti bancari per il pubblico, le banche centrali +entrerebbero in diretta concorrenza con le banche commerciali, competizione +che comporterebbe due rischi. In primo luogo, potrebbe minacciare la base +dei depositi delle banche e, all'estremo, portare alla disintermediazione +bancaria. Ciò potrebbe influire negativamente sulla disponibilità di +credito per il settore privato e, di conseguenza, sull'attività +economica~\cite[][]{Agur}. La disintermediazione delle banche potrebbe anche +condurre alla centralizzazione dell'allocazione del credito all'interno +della banca centrale, con ripercussioni negative sulla produttività e +sulla crescita economica. In secondo luogo, la possibilità per le persone +di trasferire i propri depositi nel porto sicuro di una banca centrale +potrebbe accelerare le corse agli sportelli nei periodi di crisi economica. + +Vi sono però argomentazioni contrarie. \cite{Brunnermeier} +sostengono che i trasferimenti di fondi dai depositi ai conti +CBDC porterebbero alla sostituzione automatica del finanziamento +mediante depositi con il finanziamento tramite la banca centrale, il +che andrebbe ad esplicitare la garanzia finora implicita di prestatore +di ultima istanza delle banche centrali. \cite{Berentsen} +sostengono che la concorrenza delle banche centrali potrebbe persino +avere un effetto disciplinare sulle banche commerciali e quindi +aumentare la stabilità del sistema finanziario, dato che queste ultime +sarebbero costrette a consolidare la sicurezza dei propri modelli +economici per eviatare corse agli sportelli. + +% References to Kumhof, Bindseil below should render like this: +% valore (Kumhof &amp; Noone, 2018 e Bindseil, 2020). +% This was fixed by replacing "," with "and" to separate authors in the bib file. +% It also fixed {Kumhof} to render as "Kumhof & Noone". + +Esistono anche proposte per ridurre il rischio di disintermediazione +restringendo o scoraggiando l'uso della CBDC come riserva di valore. Una +delle proposte è di limitare la quantità di CBDC che si può possedere. +Una seconda proposta consiste nell'applicare un tasso di interesse +variabile ai conti in CBDC, in modo che il rendimento sia sempre +sufficientemente inferiore a quello dei conti nelle banche commerciali, +arrivando eventualmente fino a tassi negativi, in modo da rendere la CBDC +meno attraente come riserva di valore~\cite[][]{Kumhof,Bindseil}. Oltre a ciò, +per evitare le corse agli sportelli \citet{Kumhof} suggeriscono che la +CBDC non dovrebbe essere emessa a fronte di depositi bancari ma solo a +fronte di obbligazioni come i titoli di stato. Nel complesso, una CBDC +basata su conti richiederebbe un'analisi più approfondita di queste +problematiche. + +% Back to default style. +%\bibpunct{(}{)}{ e }{,}{}{,} + + +\subsection{CBDC Basata su token e legata al hardware} +\label{cbdc-basata-su-token-e-legata-al-hardware} + +% References to Wojtczuk,Johnston,Lapid below do not render correctly in pdf. Should be: +% compromesse (si veda, ad esempio, Wojtczuk &amp; Rutkowska 2009, Johnston 2010 e Lapid &amp; Wool 2018). +% but we can only either use "," or "e", but not switch AFAIK. +% This was fixed by replacing "," with "and" to separate authors in the bib file. +% It also fixed {Katzenbeisser} to render as "Katzenbeisser et al." + +In alternativa ai conti deposito, una banca centrale potrebbe emettere +token elettronici. Tecnicamente ciò richiede un sistema per garantire che +i token elettronici non possano essere copiati facilmente. Le funzioni +fisicamente non clonabili~\cite[vedi][]{Katzenbeisser} e le aree +sicure nell'hardware~\cite[vedi][]{Alves,Pinto} sono due tecnologie +possibili per la prevenzione della copia digitale. Le funzioni +fisicamente non clonabili, tuttavia, non possono essere scambiate su +Internet (eliminando di fatto l'uso principale delle CBDC) e le precedenti +funzionalità di sicurezza nell'hardware per la prevenzione della copia +sono state ripetutamente +compromesse~\cite[si veda, ad esempio,][]{Wojtczuk,Johnston,Lapid}. + +Un vantaggio fondamentale delle CBDC basate su token rispetto a quelle +basate su conti è che i sistemi tokenizzati funzionerebbero offline, +ovvero, gli utenti potrebbero scambiare token (\textit{peer-to-peer}) +senza coinvolgere la banca centrale, proteggendo così la privacy e la +libertà delle persone. Tuttavia, la disintermediazione che si verifica +quando gli utenti possono scambiare token elettronici senza +intermediari bancari che eseguano i controlli per la conoscenza dei +clienti e le procedure per la lotta al riciclaggio di denaro e al +finanziamento del terrorismo renderebbe difficile la lotta alla +criminalità. + +% References to Soukup,Garcia,Kasper,CCC below do not render correctly in pdf. Should be: +% L’esperienza (si veda, ad esempio, Soukup &amp; Muff 2007, Garcia et al. 2008, Kasper et al. 2010 e CCC e.V. 2017) suggerisce +% but we can only either use "," or "e", but not switch AFAIK. +% This was fixed by replacing "," with "and" to separate authors in the bib file. + +Le schede SIM sono oggi il mezzo più ampiamente disponibile per un +sistema di pagamento sicuro basato su hardware, ma comportano anche +dei rischi. L'esperienza~\cite[si veda, ad esempio,][]{Soukup,Garcia,Kasper,CCC} +suggerisce che qualsiasi dispositivo economicamente riproducibile in grado +di memorizzare token con valore monetario, che una persona possa possedere +e che consenta transazioni offline --- e quindi il furto mediante +clonazione delle informazioni in esso contenute --- sarà l'obiettivo di +attacchi di contraffazione riusciti non appena il valore economico +dell'attacco risulti sostanziale. Tali attacchi provengono anche da +utenti che forzano il proprio hardware~\cite[vedi][]{Allen}. Per +limitare l'impatto di una compromissione, i sistemi con carte di pagamento +che sono stati precedentemente implementati dipendono dalla resistenza +alle manomissioni in combinazione con il rilevamento delle frodi. +Tuttavia, il rilevamento delle frodi richiede la capacità di identificare +i pagatori e tenere traccia dei clienti, il che non è compatibile con la +privacy nelle transazioni. + +\section{Una CBDC basata su token progettata per tutelare la privacy} +\label{4.-una-cbdc-basata-su-token-progettata-per-tutelare-la-privacy} + +La CBDC qui proposta è di tipo «solo software», semplicemente +un'applicazione per smartphone che non richiede alcun hardware aggiuntivo. +Il design fa affidamento su eCash e GNU Taler. Taler fa parte del progetto +GNU, il cui fondatore, Richard Stallman, ha coniato il termine +«\emph{Software Libero}», ora spesso indicato come \textit{Free/Libre +and Open Source Software} (FLOSS).\footnote{Per ulteriori informazioni +su GNU, si veda \url{https://www.gnu.org} e \cite{Stallman}. GNU Taler +è rilasciato sotto la licenza libera \textit{GNU Affero General Public +License} del Progetto GNU. Altri programmi del progetto GNU noti tra gli +economisti sono \textit{R} e \textit{GNU Regression, Econometrics and +Time-series Library} (GRETL). Per un'analisi dei vantaggi del FLOSS +rispetto al software proprietario nel campo della ricerca, si +veda~\cite{Baiocchi}, \cite{Yalta2008} e \cite{Yalta2010}. +Sulle licenze libere e open source, si veda~\cite{Lerner}.} Il software +è considerato libero se la sua licenza concede agli utenti quattro libertà +essenziali: la libertà di eseguire il programma come si desidera, la +libertà di studiare il programma e modificarlo, la libertà di ridistribuire +copie del programma e la libertà di distribuire copie delle versioni +modificate del programma. Il software libero non impedisce la +commercializzazione; fornire supporto tecnico per il software è un modello +di business standard per il FLOSS. + +Dato il gran numero di parti interessate coinvolte in una CBDC al +dettaglio (la banca centrale, il settore finanziario, i venditori e +i clienti) e l'importanza critica dell'infrastruttura, una CBDC al +dettaglio deve essere basata sul FLOSS. Imporre una soluzione +proprietaria, che comporta la dipendenza da un fornitore specifico, +sarebbe probabilmente un ostacolo all'adozione fin dall'inizio. Con il +FLOSS, tutte le parti interessate hanno accesso a ogni dettaglio della +soluzione e il diritto di adattare il software alle proprie esigenze. +Ciò facilita l'integrazione e migliora l'interoperabilità e la +concorrenza tra i fornitori.\footnote{Tuttavia, l'hardware privato +potrebbe avere un ruolo da svolgere. La protezione degli archivi delle +chiavi e di alcune funzioni di controllo, ad esempio, può essere un'area +dove l'hardware dedicato valutato solo da un numero limitato di esperti +può presentare dei vantaggi, nella misura in cui tale sicurezza sia solo +additiva.} Consente inoltre alla banca centrale di soddisfare i requisiti +di trasparenza e responsabilità. I vantaggi del FLOSS riguardo la +sicurezza sono anche ampiamente riconosciuti. La disponibilità del codice +sorgente e la libertà di modificarlo facilitano l'identificazione degli +errori e la loro rapida correzione. \footnote{Ad esempio, un bollettino +sulla sicurezza informatica emesso dall'Agenzia per la sicurezza nazionale +degli Stati Uniti (NSA) nell'aprile 2020 esorta gli utenti a dare la +priorità al software libero nella scelta e nell'utilizzo dei servizi +collaborativi per le comunicazioni su Internet: «Lo sviluppo open source +garantisce trasparenza sulla robustezza del codice e la sua conformità +alle migliori pratiche di programmazione, evitando l'introduzione di +vulnerabilità o punti deboli che potrebbero mettere a rischio utenti e +dati» (U/OO/134598-20).} + +Nell'architettura che proponiamo, tutte le interazioni tra consumatori +e venditori si fanno con le banche commerciali, ma la creazione di moneta +e il database sono forniti esclusivamente dalla banca centrale. Le banche +commerciali autenticano i clienti quando ritirano CBDC così come i +venditori o beneficiari quando le ricevono. Quando spendono CBDC, +invece, i clienti o pagatori devono solo autorizzare le transazioni senza +bisogno di identificarsi. I pagamenti risultano più economici, più facili +e più veloci, evitando al contempo interferenze con la privacy~\cite[][]{Dold}. +L'autenticazione dei clienti quando ritirano CBDC, nonché dei venditori +o beneficiari quando le ricevono, consente altresì di adempire alle +normative sulla conoscenza dei clienti e sulla lotta al riciclaggio di +denaro e al finanziamento del terrorismo. + +La CBDC che si propone in questo documento è un vero e proprio +strumento digitale al portatore perché quando l'utente preleva una +somma di denaro sotto forma di numero, tale numero viene «accecato» o +nascosto dallo smartphone con un'apposita crittografia. Nel sistema +stesso, una moneta è una coppia di chiavi pubblica-privata dove la +chiave privata è nota solo al proprietario della moneta.\footnote{In +Bitcoin, un sistema basato su conti, la coppia di chiavi è un conto +dove la chiave pubblica rappresenta l'«indirizzo» e quindi una sorta di +«identità», anche se pseudonimo.} La moneta trae il suo valore +finanziario dalla firma della banca centrale apposta sulla chiave +pubblica della moneta. La banca centrale firma con la propria chiave +privata e detiene più coppie di chiavi di valore per apporre la firma +cieca su monete di diverso valore unitario. Il venditore può utilizzare +la corrispondente «chiave pubblica» della banca centrale per verificare +la firma. Tuttavia, al fine di garantire che la moneta non sia stata +copiata e già ritirata da un altro beneficiario (cioè che non sia stata +«spesa due volte»), il venditore deve depositare la moneta affinché la +banca centrale possa confrontarla con un archivio di monete ritirate. +Poiché né la banca commerciale né la banca centrale vedono il numero +della moneta durante il prelievo, in seguito, quando il venditore +deposita la moneta, non si sa quale utente l'abbia ritirata. L'accecamento +e la privacy che ne deriva fanno di questa tipologia di CBDC un vero e +proprio strumento digitale al portatore. + +Nell'analisi che segue forniamo una panoramica approfondita della +tecnologia e mostriamo come si può integrare con il sistema bancario +esistente per creare una CBDC. \citet{Dold} fornisce ulteriori +dettagli. + +\subsection{Componenti fondamentali}\label{componenti-fondamentali} + +Di seguito si descrivono i componenti principali del protocollo, comprese +le basi matematiche per una delle possibili rappresentazioni delle +primitive crittografiche utilizzate, allo scopo di illustrare in +che modo potrebbe funzionare un'implementazione. Considerando che +esistono altri modelli matematici equivalenti per ciascun componente, +presentiamo solo la più semplice delle soluzioni sicure a noi note. + +\emph{Firme digitali.} L'idea che sta alla base delle firme digitali in +uno schema di firma a chiave pubblica è quella di garantire che il +titolare della chiave privata sia l'unico in grado di firmare un +messaggio, mentre la chiave pubblica consente a chiunque di verificare +la validità della firma.\footnote{La crittografia a chiave pubblica è +stata introdotta da~\cite{Diffie} e le prime implementazioni di firme +digitali sono state quelle di~\cite{Rivest}.} Il risultato della funzione +di verifica della firma è la dichiarazione binaria «vero» o «falso». Se +il messaggio è firmato con la chiave privata che appartiene alla chiave +pubblica di verifica, il risultato è «vero», altrimenti è «falso». +Nella nostra proposta il messaggio è una moneta o una banconota con un +numero di serie, e la firma della banca centrale ne attesta la +validità. Sebbene GNU Taler utilizzi per impostazione predefinita le +moderne firme EdDSA~\cite[vedi][]{Bernstein2012}, qui presentiamo un +semplice schema di firma crittografica basato su RSA~\cite[][]{Rivest}, un +sistema crittografico ben studiato.\footnote{Per un'analisi della +lunga storia del crittosistema RSA e uno studio degli attacchi a questo +sistema, si veda~\cite{Boneh}.} Tuttavia, in linea di principio, è +possibile utilizzare qualsiasi tecnologia di firma crittografica +(DSA, ECDSA, EdDSA, RSA, ecc.) + + +Per generare una chiave RSA, il firmatario prende prima due grandi +numeri primi indipendenti $p$ e $q$ e calcola $n = \emph{pq}$, +nonché la funzione phi di Eulero +$\phi(n) = (p - 1)(q - 1)$. +Quindi, si può utilizzare qualsiasi $e$ con $1 < e < \phi(n)$ e +$\gcd(e, \phi(n)) = 1$ per definire una chiave pubblica $(e,n)$. +La condizione che il massimo comune denominatore ($\texttt{MCD}$) di $e$ e +$\phi(n)$ debba essere 1 (cioè, che devono essere +primi tra loro) assicura che l'inverso di +$e \mod \phi(n)$ esista. +Questo inverso è la +corrispondente chiave privata $d$. Data $\phi(n)$, la chiave +privata $d$ può essere calcolata mediante l'algoritmo esteso +di Euclide tale che +$d \cdot e \equiv 1 \mod \phi(n)$. + +Data la chiave privata $d$ e la chiave pubblica $(e, n)$, una semplice +firma RSA +$s$ su un messaggio $m$ è +$s \equiv m^{d} \mod n$. +Per verificare la firma si calcola +$m' \equiv s^{e} \mod n$. +Se $m'$ e $m$ corrispondono, la firma è valida e dimostra che il +messaggio è stato firmato con la chiave privata che corrisponde alla +chiave pubblica di verifica (autenticazione del messaggio) e che il +messaggio non è stato modificato durante il transito (integrità del +messaggio). In pratica, le firme vengono poste sull'hash dei messaggi +piuttosto che sui messaggi stessi. Le funzioni di hash calcolano le +impronte digitali dei messaggi (\textit{digest}), che sono identificatori +univoci e brevi per i messaggi. Firmare un hash breve è molto più veloce +che firmare un messaggio di grandi dimensioni, e la maggior parte degli +algoritmi di firma funzionano solo su input relativamente brevi.\footnote{Nel +caso del crittosistema RSA, il limite di lunghezza è di +$\log_{2}n$ bit.} + +\emph{Firme cieche.} Utilizziamo le firme cieche introdotte +da~\cite{Chaum1983} per tutelare la privacy degli acquirenti. Una firma +cieca viene utilizzata per creare una firma crittografica per un messaggio +senza rivelare al firmatario il contenuto del messaggio. Nella nostra proposta, +ciò impedisce alle banche commerciali e alla banca centrale di poter risalire +all'acquirente tracciando gli acquisti. In linea di principio, la nostra +proposta funziona con qualsiasi sistema di firma cieca, ma la soluzione migliore +rimane la variante basata su RSA descritta da~\cite{Chaum1983}. + +L'accecamento viene eseguito dai clienti, che accecano le proprie +monete prima di trasmetterle alla banca centrale per la firma. I +clienti non devono quindi affidare alla banca centrale la tutela della +propria privacy. Inoltre, l'accecamento con RSA fornirebbe protezione +della privacy anche contro gli attacchi informatici quantistici. La +banca centrale, dal canto suo, predispone più coppie di chiavi di +valore per apporre la firma cieca su monete di diverso valore +unitario, e fornisce le corrispondenti chiavi pubbliche +$(e, n)$ per tali valori. + +Sia $f$ il valore di hash di una moneta e quindi l'identificatore +univoco per questa moneta. Il cliente che preleva la moneta prima +genera un fattore di accecamento casuale $b$ e calcola +$f' \equiv fb^{e} \mod n$ +con la chiave pubblica della banca centrale per quel valore. +La moneta accecata $f'$ viene quindi trasmessa alla banca centrale per +la firma. La banca centrale firma $f'$ con la sua chiave +privata $d$ calcolando la firma cieca +$s' \equiv \left(f' \right)^{d} \mod n$, appone +la firma $s'$ alla moneta accecata $f'$ e restituisce la coppia +$(s',f')$ al cliente. Il cliente può quindi rimuovere l'accecamento +della firma calcolando +$s \equiv s'b^{- 1} \mod n$. +Ciò è possibile perché +$\left( f' \right)^d = f^db^{ed} = f^db$, e quindi +moltiplicando $s'$ con $b^{- 1}$ si ottiene $f^d$, che è una firma RSA +valida su $f$ come prima: +$s^e \equiv f^{de} \equiv f \mod n$. + +Nella proposta originale di Chaum, le monete erano dei semplici +gettoni. Quel che vogliamo, invece, è che i consumatori possano +utilizzare le firme digitali per stipulare contratti. A tal fine, ogni +volta che un portafoglio digitale preleva una moneta, in primo luogo +crea per la moneta una chiave privata casuale $c$ e calcola la +corrispondente chiave pubblica $C$ per creare firme digitali con i +normali sistemi di firma crittografica (come DSA, ECDSA, EdDSA e +RSA). Quindi si deriva $f$ mediante una funzione di hash crittografica +dalla chiave pubblica $C$, prima che la banca centrale ne apponga la +firma cieca (utilizzando un nuovo fattore di accecamento casuale per +ciascuna moneta). Ora il cliente può utilizzare $c$ per firmare +elettronicamente gli acquisti, spendendo così la moneta. + +Come visto sopra, la banca centrale andrebbe a predisporre coppie di +chiavi diverse per ogni valore unitario di moneta e pubblicherebbe le +chiavi pubbliche che i clienti userebbero per prelevare denaro. Queste +chiavi di valore, e quindi le monete, avrebbero una data di scadenza +prima della quale dovrebbero essere spese o scambiate con monete +nuove. Ai clienti verrebbe concesso un certo periodo di tempo per +scambiare le monete. Un processo simile esiste per le banconote +fisiche, dove le serie di banconote vengono regolarmente rinnovate per +essere dotate delle più recenti caratteristiche di sicurezza, tranne +per il fatto che le banconote generalmente rimangono in circolazione +per decenni anziché per pochi anni o mesi.\footnote{In Svizzera, +ad esempio, la Banca nazionale svizzera ha iniziato a ritirare dalla +circolazione l'ottava serie di banconote nell'aprile 2016. Questa serie +era stata messa in circolazione alla fine degli anni novanta. Dal 1 +gennaio 2020, tuttavia, tutte le banconote a partire dalla sesta serie +(emesse nel 1976) fino alle serie future restano valide e possono essere +scambiate a tempo indeterminato con banconote correnti.} + +Da un punto di vista tecnico, una data di scadenza offre due vantaggi. +In primo luogo, migliora l'efficienza del sistema perché la banca +centrale può cancellare i dati scaduti, evitando così di dover +archiviare e poi cercare in un elenco sempre crescente di monete +(spese) per rilevare una doppia spesa. In secondo luogo, riduce i +rischi per la sicurezza dato che la banca centrale non deve +preoccuparsi di attacchi alle proprie chiavi (private) di valore ($d$) +scadute. Inoltre, anche se una chiave privata venisse compromessa, il +periodo durante il quale l'attaccante può utilizzarla è breve. In aggiunta, +l'addebito di una commissione di cambio consentirebbe alla banca centrale di +applicare tassi di interesse negativi, se ritenuto necessario. La banca centrale +potrebbe anche, se lo desidera, fissare un limite di conversione per cliente in +considerazione dell'antiriciclaggio e l'antiterrorismo (soglia di «contante») o +per motivi di stabilità finanziaria (per prevenire accaparramenti e corse agli +sportelli). + +\emph{Protocollo di scambio di chiavi.} GNU Taler utilizza un protocollo +di scambio di chiavi in un modo particolare per fornire un collegamento +tra la moneta originale e il resto reso per quella stessa moneta. Ciò +garantisce che il resto possa sempre essere reso senza compromettere +la trasparenza del reddito e la privacy dei consumatori. Lo stesso +meccanismo si può utilizzare per i rimborsi anonimi ai clienti. Il +protocollo gestisce anche i guasti alla rete e ai componenti, +assicurando che i pagamenti siano andati a buon fine o siano stati +definitivamente annullati e che tutte le parti abbiano una prova +crittografica dell'esito. Questo corrisponde all'incirca agli scambi +atomici nei protocolli \textit{interledger} o allo scambio equo nei +tradizionali sistemi \textit{e-cash}. + +La costruzione matematica più comune per un protocollo di scambio di +chiavi è la costruzione~\cite{Diffie}, che +consente a due parti di derivare una chiave segreta condivisa. A tale +scopo, condividono due parametri di dominio $p$ e $g$, che possono +essere pubblici, dove $p$ è un numero primo grande e $g$ è una radice +primitiva modulo $p$.\footnote{Un intero $g$ è una radice primitiva +modulo $p$ se per ogni intero $a$ coprimo a $p$ esiste un intero $k$ +per il quale +$g^k \equiv a \mod p$. +In pratica, $g$ dovrebbe essere una radice primitiva $(p-1)$-esima, detta +anche generatore, al fine di prevenire attacchi a sottogruppi come quelli +Pohlig-Hellman~\cite[vedi][]{Lim}.} Ora, le due parti scelgono le loro +chiavi private \emph{a} e \emph{b}, che sono due numeri interi grandi. +Con queste chiavi private e i parametri di dominio, generano le +rispettive chiavi pubbliche +$A \equiv g^{a} \mod p$ e $B \equiv g^{b} \mod p$. +Ciascuna parte può ora utilizzare la propria chiave privata e la chiave +pubblica dell'altra parte per calcolare la chiave segreta condivisa +$k \equiv \left( g^b \right)^{a} \equiv \left( g^{a} \right)^{b} \equiv g^{\text{ab}} \mod p$.\footnote{ +Lo stesso meccanismo potrebbe essere utilizzato per garantire +che le monete non vengano trasferite a terzi durante il prelievo. A +questo scopo, gli utenti devono salvaguardare una chiave di identità a +lungo termine. Il processo di prelievo potrebbe quindi essere +costruito allo stesso modo di quello utilizzato da GNU Taler per dare +il resto, tranne per il fatto che quando si preleva dal conto bancario +del cliente verrebbe utilizzata la chiave d'identità a lungo termine +del cliente al posto della moneta originale. Tuttavia, le garanzie +sulla privacy potrebbero decadere se il cliente non protegge la chiave +d'identità a lungo termine, con il conseguente rischio di furto di +tutte le monete residue. Dato che il rischio nei trasferimenti a terzi +quando si prelevano monete è basso, non è chiaro se questa riduzione +del rischio possa essere un buon compromesso.} + +Per ottenere il resto, il cliente parte dalla chiave privata della +moneta parzialmente spesa $c$. Sia $C$ la chiave pubblica corrispondente, +per esempio +$C = g^{c} \mod p$. +Quando la moneta fu parzialmente spesa in precedenza, la banca centrale +registrò la transazione relativa a $C$ nel proprio database. Per +semplicità, assumiamo che esista un valore unitario che corrisponda +esattamente a questo valore residuo. In caso contrario, il protocollo si +riavvia finché non viene reso tutto il resto. Sia $(e,n)$ la +chiave di valore per il resto da rendere. + +Per ottenere il resto, l'acquirente crea prima $\kappa$ chiavi di +trasferimento private $t_{i}$ per \\ +$i \in \left\{ 1,\ldots,\kappa \right\}$ e calcola le +corrispondenti chiavi pubbliche $T_{i}$. Queste chiavi di +trasferimento $\kappa$ sono semplicemente coppie di chiavi +pubbliche-private che consentono al cliente di eseguire localmente il +protocollo di scambio di chiavi, con il cliente che gioca su entrambi +i lati del processo, $\kappa$ volte tra $c$ e ogni $t_{i}$. +Se si usa Diffie-Hellman come protocollo per lo scambio di chiavi, si +ottiene +$T_{i} \equiv g^{t_{i}} \mod p$. + +Il risultato è composto da tre trasferimenti +$K_{i} \equiv \emph{KX}(c,t_{i})$. Il protocollo di scambio di chiavi +può essere utilizzato in diversi modi per ottenere lo stesso valore +$K_{i} \equiv \emph{KX}(C,t_{i}) = \emph{KX}(c,T_{i})$. +Data $K_{i}$, il cliente utilizza una funzione crittografica hash $H$ +per ricavare i valori +$(b_{i},c_{i}) \equiv H(K_{i})$, dove +$b_{i}$ è un fattore di accecamento valido per la chiave di valore +$(e,n)$ e $c_{i}$ +è una chiave privata per la nuova moneta da ottenere come resto. +$c_{i}$ deve essere adatta sia per creare firme crittografiche sia per +un uso futuro con il protocollo di scambio di chiavi +(come $c$, per ottenere resto a partire dal resto). +Sia $C_{i}$ la chiave pubblica corrispondente a $c_{i}$. +Il cliente chiede quindi alla banca centrale di creare una firma cieca su +$C_{i}$ per $i \in \{ 1,\ldots,\kappa\}$.\footnote{Se dovesse essere +utilizzato il crittosistema RSA per le firme cieche, useremmo +$f \equiv \emph{FDH}_{n}(C_{i})$, dove +$\emph{FDH}_{n}()$ +è l'hash del dominio completo sul dominio $n$.} In questa richiesta, il +cliente si impegna anche con le chiavi pubbliche +$T_{i}$. +La richiesta è autorizzata mediante una firma effettuata con la chiave +privata $c$. + +Invece di restituire direttamente la firma cieca, la banca centrale +chiede prima al cliente di dimostrare che ha utilizzato correttamente la +costruzione di cui sopra fornendo +$\gamma \in \left\{ 1,\ldots,\kappa \right\}$. +Il cliente deve quindi mostrare alla banca centrale la +$t_{i}$ per $i \neq \gamma$. +La banca centrale può quindi calcolare +$K_{i} \equiv \emph{KX}(C,t_{i})$ e ricavare i valori +$(b_{i},c_{i})$. Se per tutte le +$i \neq \gamma$ la $t_{i}$ fornita dimostra che il cliente ha utilizzato +correttamente la costruzione, la banca centrale restituisce la firma +cieca su $C_{\gamma}$. +Se il cliente non fornisce una prova corretta, il valore residuo della +moneta originale viene perso. Questo penalizza efficacemente coloro che +tentano di eludere la trasparenza del reddito con un'aliquota fiscale +stimata di $1 - \frac{1}{\kappa}$. + +Per evitare che un cliente cospiri con un venditore che sta tentando di +evadere il fisco, la banca centrale consente a chiunque +conosca $C$ di ottenere, in qualsiasi momento, i valori di +$T_{\gamma}$ +e le firme cieche di tutte le monete collegate alla moneta originaria $C$. +Ciò permette al possessore della moneta originaria, che conosce $c$, di +calcolare +$K_{\gamma} \equiv \emph{KX}( c,T_{\gamma})$ +e da lì ricavare +$(b_{i},c_{i})$ +per, infine, rimuovere la firma cieca. Di conseguenza, un venditore che +nasconde il proprio reddito in questo modo formerebbe solo un'accordo +economico limitato con il cliente invece di ottenere il controllo esclusivo. + +\hypertarget{architettura-del-sistema}{% +\subsection{Architettura del sistema}\label{architettura-del-sistema}} + +Uno degli obiettivi principali della nostra architettura è garantire +che le banche centrali non debbano interagire direttamente con i +clienti né conservare alcuna informazione su di loro, ma solo tenere +un elenco delle monete spese. L'autenticazione è delegata alle banche +commerciali, che dispongono già dell'infrastruttura necessaria. I +protocolli di prelievo e deposito raggiungono la banca centrale +tramite una banca commerciale in qualità di intermediaria. Dal punto +di vista del cliente, il processo è analogo al prelievo di contanti da +un bancomat. La transazione tra la banca commerciale dell'utente e la +banca centrale avviene in background. La procedura per il prelievo di +CBDC è illustrata nel diagramma~\ref{fig:fig1}. + +\begin{figure}[h!] + \includegraphics[width=\textwidth]{diagramma1-it.png} + \caption{Prelievo di CBDC} + \label{fig:fig1} +\end{figure} + +Il cliente (1) invia i dati di accesso alla propria banca commerciale +utilizzando le relative procedure di autenticazione e autorizzazione. +Quindi il telefono (o il computer) del cliente ottiene la chiave di +valore pubblica $(e, n)$ fornita dalla banca centrale per quel valore; (2) +calcola quindi una coppia di chiavi per la moneta, con una chiave +privata $c$ e una chiave pubblica $C$, e sceglie un fattore di accecamento +$b$. La chiave pubblica della moneta viene quindi sottoposta a hash \\ +($\to$ $f$) e accecata ($\to$ $f'$). Quindi il dispositivo del cliente (3) +invia $f'$ insieme all'autorizzazione a prelevare la moneta e ad +addebitarla dal conto del cliente presso la banca commerciale tramite un +canale sicuro stabilito. La banca commerciale (4) addebita quindi +l'importo dal conto deposito del cliente, (5) autorizza digitalmente la +richiesta utilizzando la firma digitale specifica della propria filiale +e inoltra la richiesta e la moneta accecata alla banca centrale per la +firma. La banca centrale (6) sottrae il valore della moneta dal conto +della banca commerciale, appone la firma cieca sulla moneta +utilizzando la chiave privata che detiene per il relativo valore e (7) +restituisce la firma cieca $s'$ alla banca commerciale. La banca +commerciale (8) inoltra la firma cieca $s'$ al portafoglio elettronico +del cliente. Infine, il dispositivo del cliente (9) utilizza $b$ per +rimuovere l'accecamento dalla firma ($\to$ $f$) e salva la moneta appena +coniata $(c, s)$. + +Per spendere CBDC, la procedura è analoga al pagamento in contanti. +Tuttavia, per consolidare la transazione, il venditore deve depositare +la moneta. La procedura per spendere CBDC è illustrata nel diagramma 2. + +\begin{figure}[h!] + \includegraphics[width=\textwidth]{diagramma2-it.png} + \caption{Spendere e depositare CBDC} + \label{fig:fig2} +\end{figure} + +Un cliente e un venditore negoziano un contratto commerciale. Il +cliente (1) utilizza una moneta elettronica per firmare il contratto o +l'atto di vendita con la chiave privata $c$ della moneta e trasmette la +firma al venditore. La firma di una moneta su un contratto con una +moneta valida è l'istruzione del cliente di pagare il venditore, che è +identificato dal conto bancario nel contratto. Se una singola moneta +non fosse sufficiente per coprire l'importo totale, i clienti possono +firmare il contratto con più monete. Il venditore (2) convalida quindi +la firma della moneta sul contratto e la firma $s$ della banca centrale +su $f$, che corrisponde a quella della moneta $C$ con le rispettive +chiavi pubbliche, e inoltra la moneta firmata (insieme alle +informazioni sul conto del venditore) alla banca commerciale del +venditore. La banca commerciale del venditore (3) conferma che il +venditore è un suo cliente e inoltra la moneta firmata alla banca +centrale. La banca centrale (4) verifica le firme e controlla il +proprio database per accertarsi che la moneta non sia già stata spesa. +Se tutto è in ordine, la banca centrale (5) aggiunge la moneta +all'elenco delle monete spese, l'accredita sul conto della banca +commerciale presso la banca centrale e (6) invia una conferma in tal +senso alla banca commerciale. Quindi la banca commerciale (7) +accredita la moneta sul conto del venditore e (8) gli invia una +notifica. Il venditore (9) consegna il prodotto o servizio al cliente. +L'intera operazione richiede poche centinaia di millisecondi. + +\hypertarget{considerazioni-sulla-sicurezza}{% +\subsection{Considerazioni sulla sicurezza} +\label{considerazioni-sulla-sicurezza}} + +Nella nostra proposta, occorre che la banca centrale gestisca un +database e un servizio online ad alta disponibilità. Poiché le monete +elettroniche possono essere copiate dagli utenti, solo con i controlli +online si può prevenire in modo efficace la doppia spesa. Sebbene +nella teoria esistano soluzioni per identificare a posteriori gli +utenti che effettuano una doppia spesa~\cite[vedi][]{Chaum1990}, +queste soluzioni creano rischi economici sia per gli utenti che per la +banca centrale a causa del ritardo nell'identificazione di +transazioni fraudolente. Il rilevamento online della doppia spesa +elimina questo rischio, ma significa anche che sarà impossibile +effettuare le transazioni se la connessione Internet alla banca +centrale non è disponibile. + +La banca centrale dovrà anche proteggere la riservatezza delle chiavi +private che utilizza per firmare le monete e altri messaggi di +protocollo. Se le chiavi di firma della banca centrale dovessero +essere compromesse, ad esempio da un computer quantistico, da un +attacco fisico ai \textit{datacenter} o anche da qualche nuovo algoritmo +% FIXME: +% forme alternative: +% 1) "rimborsare AGLI utenti ... tutte le monete non spese" +% 2) "rimborsare gli utenti ... DI tutte le monete non spese" +%FIXED +imprevisto, è possibile rimborsare agli utenti --- in tutta sicurezza e +senza compromettere la privacy --- tutte le monete non spese. La banca +centrale annuncerebbe la revoca della chiave tramite l'\textit{Application +Programming Interface} (API), che verrebbe rilevata dai portafogli, +avviando quindi il seguente protocollo di aggiornamento: l'utente +svela alla banca centrale la chiave pubblica $C$ della moneta, la firma +$s$ della banca centrale e il fattore di accecamento $b$, consentendo così +alla banca centrale di verificare il legittimo prelievo dell'utente e +di rimborsare il valore della moneta non spesa. Per rilevare una +possibile compromissione della propria chiave, la banca centrale può +monitorare il database in cerca di depositi che eccedano i prelievi. + +\subsection{Scalabilità e costi}\label{scalabilità-e-costi} + +Lo schema che proponiamo sarebbe efficiente ed economico quanto i +moderni sistemi RTGS attualmente utilizzati dalle banche centrali. + +La scalabilità si riferisce al costo di aumentare la potenza di +calcolo in modo che si possa concludere un numero crescente di +transazioni in tempi adeguati. Il costo complessivo del sistema può +essere basso in quanto la CBDC qui proposta si basa interamente su +software. Le monete spese devono essere conservate fino alla scadenza +della coppia di chiavi di valore utilizzata per firmare le monete, ad +esempio tramite un ciclo annuale continuo, che mantiene limitata la +dimensione del database. La potenza di calcolo e la larghezza di banda +necessarie aumentano della stessa quantità per ogni transazione, spesa +o deposito addizionali, dato che le transazioni sono intrinsecamente +indipendenti l'una dall'altra. Questa ulteriore potenza si ottiene +semplicemente aggiungendo più hardware, una pratica spesso conosciuta +come partizionamento o \textit{sharding}. Grazie al cosiddetto +\textit{consistent hashing}, le aggiunte di hardware non risultano +dirompenti. Si può anche utilizzare qualsiasi tipo di database. + +Più nello specifico, la logica del \textit{front-end} presso la banca +centrale deve solo eseguire poche operazioni di firma, e un singolo +processore può eseguirne alcune migliaia al secondo~\cite[vedi][]{Bernstein2020}. +Se un unico sistema non fosse sufficiente, è facile aggiungere altri +server \textit{front-end} e invitare le varie banche commerciali a +bilanciare le loro richieste nella \textit{server farm} o +utilizzare un sistema di bilanciamento del carico per distribuire le +richieste all'interno dell'infrastruttura della banca centrale. + +I server \textit{front-end} devono comunicare con un database per +effettuare le transazioni e prevenire la doppia spesa. Un unico server +di database moderno dovrebbe essere in grado di gestire in modo +affidabile decine di migliaia di operazioni al secondo. Le operazioni +possono essere facilmente distribuite su più server di database +semplicemente assegnando a ciascuno un intervallo di valori da +gestire. Tale configurazione garantisce che le singole transazioni non +incrocino mai le partizioni. Pertanto, anche i sistemi \textit{back-end} +dovrebbero scalare in modo lineare con le risorse di calcolo messe a +disposizione, partendo sempre da una solida base di riferimento per un +singolo sistema. + +I \textit{front-end} devono anche comunicare con i \textit{back-end} per +mezzo di un'interconnessione. Queste interconnessioni possono +supportare un gran numero di transazioni al secondo. La dimensione di +una singola transazione è in genere di circa 1–10 kilobyte. Pertanto, +i \textit{datacenter} di oggi, che scambiano informazioni a 400 Gbit/s, +possono supportare milioni di transazioni al secondo. + +%FIXME: +% +% Sotto appare "Probabilmente + congiuntivo". Suggerirei +% di cambiarlo con una forma all'indicativo. Qui si trova +% una discussione a riguardo: +% https://italian.stackexchange.com/questions/3653/probabilmente-indicativo-o-congiuntivo +% Not incorrect but FIXED anyway. +Infine, il costo totale del sistema è basso. Probabilmente il costo +principale è rappresentato dall'archiviazione sicura per +molti anni di 1–10 kilobyte per transazione. Gli esperimenti su un +prototipo di GNU Taler che utilizzava i prezzi di \textit{Amazon Web Service} +hanno stabilito che il costo del sistema (archiviazione, larghezza di +banda e capacità di calcolo) su larga scala sarebbe inferiore a +0,0001 USD per transazione~\cite[per i dettagli sui dati, si veda][]{Dold}. + +\section{Considerazioni normative e politiche} + \label{5.-considerazioni-normative-e-politiche} + +Nella soluzione che proponiamo, la banca centrale non conosce +l'identità dei consumatori o dei venditori né l'importo totale delle +transazioni, ma vede solo il momento in cui le monete elettroniche vengono +rilasciate e quando vengono riscattate. Le banche commerciali continuano a +fornire l'autenticazione cruciale di consumatori e venditori e, in particolare, +custodiscono le informazioni che acquisiscono per la conoscenza dei clienti +(KYC). Le banche commerciali osservano quando i venditori ricevono fondi e, se +necessario, possono limitare la quantità di CBDC per transazione che +un singolo venditore può ricevere. Inoltre, le transazioni sono +collegate ai relativi contratti con i clienti. La conseguente +trasparenza del reddito consente al sistema di soddisfare i requisiti +delle normative sulla lotta al riciclaggio di denaro e al +finanziamento del terrorismo (AML e CFT). In caso vengano rilevate +anomalie nei redditi dei venditori, la banca commerciale e +l'autorità fiscale o giudiziaria possono ottenere e ispezionare i +contratti relativi ai pagamenti sospetti al fine di verificarne la +legittimità. La trasparenza del reddito risultante è anche una forte +misura contro l'evasione fiscale perché i venditori non possono +sottodichiarare il proprio reddito o evadere le tasse sulle vendite. +Nel complesso, il sistema implementa gli approcci~\textit{privacy-by-design} +e \textit{privacy-by-default} (come richiesto, ad esempio, +dal Regolamento generale sulla protezione dei dati dell'UE, GDPR). I +venditori non apprendono necessariamente l'identità dei propri clienti, +le banche possiedono solo le informazioni necessarie sulle attività dei +propri clienti e la banca centrale non ha accesso ai dettagli sulle +attività dei cittadini. + +In alcuni paesi le normative impongono limiti per i prelievi e i +pagamenti in contanti. Tali restrizioni possono essere implementate +anche per la CBDC nel progetto proposto. Ad esempio, è possibile +stabilire una soglia per l'importo giornaliero che i consumatori possono +prelevare, oppure limitare l'importo totale di CBDC che le banche +commerciali possono convertire. + +La disintermediazione del settore bancario è uno dei rischi di +instabilità finanziaria spesso sollevato per quanto riguarda la CBDC +al dettaglio. In particolare, una CBDC al dettaglio potrebbe +facilitare l'accumulo di ingenti somme di denaro della banca +centrale, il che potrebbe avere un impatto negativo sul finanziamento +alle banche mediante depositi perché il pubblico deterrebbe meno +denaro sotto forma di depositi bancari. Per i paesi le cui valute +fungono da valute rifugio, ciò potrebbe anche portare ad un aumento +degli afflussi di capitali durante i periodi globali di avversione al +rischio, dando luogo ad ulteriori pressioni sui tassi di cambio. +Quello che quindi potrebbe rappresentare un serio problema nel caso di +una CBDC basata su conti, lo sarebbe molto meno con una CBDC basata +su token. Innanzitutto, l'accumulo di una CBDC basata su token comporta +rischi di furto o perdita simili a quelli legati all'accumulo di +contanti. Tenere poche centinaia di dollari su uno smartphone è +probabilmente un rischio accettabile per molti, ma detenere una somma +molto alta è probabilmente un rischio meno accettabile. Pertanto, non +ci aspettiamo un accaparramento significativamente maggiore rispetto a +quello del denaro fisico. + +Tuttavia, se l'accumulo o la massiccia conversione dei depositi +bancari in CBDC dovessero destare preoccupazione, la banca centrale +avrebbe diverse opzioni. Come si è spiegato, secondo il progetto +proposto le banche centrali fissano una data di scadenza per tutte le +chiavi di firma, il che implica che in una data prestabilita le monete +firmate con quelle chiavi diventano non valide. Alla scadenza delle +chiavi di valore, i consumatori devono scambiare con monete nuove le +monete che erano state firmate con le vecchie chiavi; l'autorità di +regolamentazione può facilmente fissare una soglia di conversione per +cliente per creare un limite rigido alla quantità di CBDC che ogni +individuo può accumulare. Inoltre, la banca centrale potrebbe addebitare +commissioni, se necessario. Una commissione di aggiornamento quando le monete +stanno per scadere significherebbe nella pratica tassi di interesse negativi +sulla CBDC per limitare il suo fascino come riserva di valore, come +suggerisce~\cite{Bindseil}. Si tratterebbe infatti della diretta attuazione +dell'idea di Silvio Gesell di applicare una tassa di possesso sulla moneta, +notoriamente citata da~\cite{Keynes} e ripresa da~\cite{Goodfriend}, +\cite{Buiter} e~\cite{Agarwal}. + +Per quanto riguarda le implicazioni in termini di politica monetaria, +non dovrebbero esserci cambiamenti reali perché la nostra CBDC è +progettata per replicare il contante piuttosto che i depositi bancari. +L'emissione, il prelievo e il deposito della nostra CBDC corrispondono +esattamente all'emissione, al prelievo e al deposito di banconote. È +possibile che la velocità di circolazione di una CBDC al dettaglio sia +diversa da quella del contante fisico, ma questo non dovrebbe +rappresentare un problema significativo per la politica monetaria. + +\hypertarget{lavori-correlati}{% +\section{Lavori correlati}\label{6.-lavori-correlati}} + +Come segnalato in precedenza, la CBDC che si propone in questo documento +si basa su eCash e GNU Taler.\footnote{L'implementazione di eCash +da parte della società DigiCash negli anni novanta è documentata su \\ +\url{https://www.chaum.com/ecash}.} A partire dalla proposta originale +e-Cash di Chaum, la ricerca si è concentrata su tre questioni principali. +In primo luogo, nella proposta originale di Chaum le monete avevano un +valore fisso e potevano essere spese solo nella loro totalità. Pagare +grandi somme con monete denominate in centesimi sarebbe stato poco +efficiente; quindi~\cite{Okamoto}, \cite{Camenisch2005}, \cite{Canard} +e~\cite{Dold} idearono modi per affrontare il problema. Queste soluzioni +comprendono protocolli per dare il resto o rendere divisibili le monete. + +Un secondo problema riguarda gli errori nelle transazioni dovuti ad +interruzioni della rete. In questo caso, il sistema deve garantire che +i fondi rimangano in possesso del consumatore senza pregiudicare la +privacy. L'\textit{Endorsed E-Cash} proposto da~\cite{Camenisch2007}, +così come da~\cite{Dold}, affrontano entrambi questo problema. Molte +delle soluzioni violano le garanzie sulla privacy per i clienti che +utilizzano queste funzionalità e tutte, tranne Taler, violano il +requisito della trasparenza del reddito. + +La terza questione importante, spesso trascurata, è la trasparenza del +reddito e quindi la conformità con i requisiti AML e KYC. \cite{Fuchsbauer} +hanno deliberatamente progettato il loro sistema di disintermediazione +per fornire una semantica più simile al contante. Tuttavia, la +disintermediazione totale è in genere difficile da concialiare con le +normative AML e KYC dato che diventa impossibile raggiungere qualsiasi +livello di responsabilità. Un esempio di tale architettura è ZCash, un +registro distribuito (\textit{ledger}) che nasconde dalla rete le +informazioni sul pagatore, sul beneficiario e sull'importo della +transazione, rendendolo quindi il sistema di pagamento perfetto per la +criminalità online. Solo Taler offre sia una privacy costante per i +clienti che la trasparenza del reddito, fornendo al contempo un sistema +di resto efficiente, scambi atomici~\cite[vedi][]{Camenisch2007} e la +possibilità di ripristinare i portafogli dal backup. + +Per quanto riguarda i sistemi di pagamento per le CBDC, \cite{Danezis} +hanno progettato un \textit{ledger} scalabile per RSCoin. Si tratta +fondamentalmente di un sistema RTGS che viene protetto utilizzando la +stessa crittografia che si usa in Bitcoin. Come Taler, il design utilizza +lo \textit{sharding} del database per consentire la scalabilità lineare. +Tuttavia, la soluzione di Danezis e Meiklejohn non prevede alcuna +disposizione per la privacy e manca di elementi per l'integrazione +pratica del design con i sistemi e i processi bancari esistenti. + +L'EUROchain della Banca Centrale Europea\cite[vedi][]{ECB} è un altro +prototipo di CBDC con registro distribuito. Simile all'architettura +proposta in questo documento, EUROchain utilizza un'architettura a due +livelli in cui le banche commerciali agiscono come intermediari. Una +differenza cruciale è il modo in cui i sistemi cercano di combinare +privacy e conformità con la normativa antiriciclaggio (AML). Mentre nel +nostro progetto l'autorità di regolamentazione può imporre un limite +alla somma di denaro elettronico che un titolare di conto bancario può +prelevare in un determinato periodo di tempo, EUROchain emette un numero +limitato di «voucher di anonimato» che garantiscono al destinatario un +numero limitato di transazioni senza controlli AML. Poiché questi voucher +sembrano essere privi di qualsiasi token di valore, non è chiaro come +il design possa impedire l'emergere di un mercato nero per i «voucher +di anonimato». Inoltre, la nozione di anonimato di EUROchain è molto +diversa, in quanto i loro «voucher di anonimato» eliminano solo alcuni +controlli AML, preservando la capacità delle banche commerciali di +sapere in che modo i clienti spendono il denaro elettronico. Laddove chi +paga utilizzando Taler interagisce direttamente con i venditori per +spendere il proprio contante elettronico, il sistema EUROchain chiede +ai pagatori di istruire le proprie banche commerciali per accedere alle +CBDC. Pertanto, EUROchain non emette direttamente token di valore ai +consumatori, affida invece ai consumatori il compito di autenticarsi +presso la propria banca commerciale per accedere alle CBDC che la +banca centrale detiene effettivamente in deposito a garanzia. Non è +quindi evidente quali siano i vantaggi di EUROchain in termini di +privacy, prestazioni o sicurezza rispetto all'attuale denaro in deposito. + +\section{Conclusione}\label{7.-conclusione} + +Con l'emergere di Bitcoin e valute digitali come Diem (già nota come +Libra) recentemente proposte dai colossi del web, le banche centrali +affrontano una crescente concorrenza da parte di operatori privati che +offrono la propria alternativa digitale al contante fisico. Le decisioni +delle banche centrali sull'emissione o meno di una CBDC dipendono dalla +loro valutazione dei benefici e dei rischi di una CBDC. È probabile che +questi vantaggi e rischi, nonché le circostanze giurisdizionali +specifiche che definiscono l'ambito di applicazione di una CBDC al +dettaglio, differiscano da un paese all'altro. + +Se una banca centrale decide di emettere una CBDC al dettaglio, +proponiamo una CBDC basata su token che combina la privacy delle +transazioni con la conformità alle normative KYC, AML e CFT. Tale CBDC +non sarebbe in concorrenza con i depositi presso le banche commerciali, +replicherebbe piuttosto il contante fisico, limitando quindi i rischi di +stabilità finanziaria e di perturbazione della politica monetaria. + +Abbiamo dimostrato che lo schema qui proposto sarebbe efficiente ed +economico quanto i moderni sistemi RTGS gestiti dalle banche centrali. +I pagamenti elettronici con la nostra CBDC richiederebbero solo un +semplice database e minuscole quantità di larghezza di banda per le +transazioni. L'efficienza e l'economicità di questa soluzione, insieme +alla maggiore facilità d'uso da parte del consumatore determinata dal +passaggio dall'autenticazione all'autorizzazione, rendono questo schema +probabilmente il primo a supportare l'annoso obiettivo dei micropagamenti +online. Inoltre, l'uso di monete per firmare crittograficamente contratti +elettronici consente anche l'impiego di contratti intelligenti. Ciò +potrebbe anche portare all'emergere di applicazioni completamente nuove +per i sistemi di pagamento. Sebbene il nostro sistema non sia basato su +DLT, può essere facilmente integrato con tali tecnologie se richiesto +dalle future infrastrutture del mercato finanziario. + +Altrettanto importante, una CBDC al dettaglio deve rimanere, come il +contante fisico, un bene rispettoso della privacy sotto il controllo +individuale dei cittadini. Lo schema proposto in questo studio soddisfa +questo criterio e consente alle banche centrali di evitare gravi sfide +alla loro politica monetaria e alla stabilità finanziaria sfruttando al +contempo i vantaggi del passaggio al digitale. + +\newpage +\bibliographystyle{agsm-mod} +\bibliography{cbdc-it} +\end{document} diff --git a/doc/cbdc-it/cbdc.bib b/doc/cbdc-it/cbdc.bib new file mode 100644 index 000000000..fe0ea6265 --- /dev/null +++ b/doc/cbdc-it/cbdc.bib @@ -0,0 +1,566 @@ +@article{Adrian, + author = {Adrian, Tobias and Tommaso Mancini-Griffoli}, + year = {2019}, + title = {The Rise of Digital Money}, + journal = {IMF Fintech Note}, + volume = {19/01}, +} + +@article{Agarwal, + author = {Agarwal, Ruchir and Miles S. Kimball}, + year = {2019}, + title = {Enabling Deep Negative Rates to Fight Recessions: A Guide}, + journal = {IMF Working Paper}, + volume = {19/84}, +} + + +@article{Agur, + author = {Agur, Itai and Anil Ari and Giovanni Dell'Ariccia}, + year = {2019}, + title = {Designing Central Bank Digital Currencies}, + journal = {IMF Working Paper}, + volume = {19/252}, +} + +@article{Allen, + author = {Allen, Sarah and Srđjan Čapkun and Ittay Eyal and Giulia Fanti and Bryan A. Ford and James Grimmelmann and Ari Juels and Kari Kostiainen and Sarah Meiklejohn and Andrew Miller and Eswar Prasad and Karl Wüst and Fan Zhang}, + year = {2020}, + title = {Design Choices for Central Bank Digital Currency: Policy and Technical Considerations}, + journal = {NBER Working Paper}, + volume = {27634}, +} + +@article{Alves, + author = {Alves, Tiago and Don Felton}, + year = {2004}, + title = {TrustZone: Integrated hardware and software security}, + journal = {ARM IQ}, + volume = {3}, + number = {4}, + pages = {18--24}, +} + +@article{AuerBoehme, + author = {Auer, Raphael and Rainer Böhme}, + year = {2020}, + title = {The technology of retail central bank digital currency}, + journal = {BIS Quarterly Review}, + month = {March}, + pages = {85--96}, +} + +@article{AuerCornelli, + author = {Auer, Raphael and Giulio Cornelli and Jon Frost}, + year = {2020}, + title = {Taking stock: ongoing retail {CBDC} projects}, + journal = {BIS Quarterly Review}, + month = {March}, + pages = {97--98}, +} + +@booklet{BIS, + author = {{Bank for International Settlements}}, + year = {2018}, + title = {Central Bank Digital Currencies. Joint Report of the Committee on Payments and Market Infrastructures and Markets Committee}, +} + +@booklet{BoE, + author = {{Bank of England}}, + year = {2020}, + title = {Central Bank Digital Currency: Opportunities, Challenges and Design. Discussion Paper}, + month = {March}, +} + +@article{Baiocchi, + author = {Baiocchi, Giovanni and Walter Distaso}, + year = {2003}, + title = {{GRETL}: Econometric Software for the {GNU} Generation}, + journal = {Journal of Applied Econometrics}, + volume = {18}, + pages = {105-110}, +} + +@article{Bech, + author = {Bech, Morten and Rodney Garratt}, + year = {2017}, + title = {Central bank cryptocurrencies}, + journal = {BIS Quarterly Review}, + month = {September}, + pages = {55--70}, +} + +@article{Berentsen, + author = {Berentsen, Aleksander and Fabian Schär}, + year = {2018}, + title = {The Case for Central Bank Electronic Money and the Non-case for Central Bank Cryptocurrencies}, + journal = {Federal Reserve Bank of St. Louis Review}, + volume = {100}, + number = {2}, + pages = {97--106}, +} + +@article{Bernstein2020, + author = {Bernstein, Daniel J. and Tanja Lange}, + year = {2020}, + title = {{eBACS}: {ECRYPT} Benchmarking of Cryptographic Systems}, + url = {\url{https://bench.cr.yp.to}, accessed 17 March 2020}, +} + +@article{Bernstein2012, + author = {Bernstein, Daniel J. and Niels Duif and Tanja Lange and Peter Schwabe and Bo-Yin Yang}, + year = {2012}, + title = {High-speed high-security signatures}, + journal = {Journal of Cryptographic Engineering}, + volume = {2}, + pages = {77--89}, +} + +@InCollection{Bindseil, + author = {Bindseil, Ulrich}, + year = {2020}, + title = {Tiered {CBDC} and the financial system}, + publisher = {European Central Bank}, + series = {ECB Working Paper}, + number = {2351}, + month = {January}, +} + +@article{Boar, + author = {Boar, Codruta and Henry Holden and Amber Wadsworth}, + year = {2020}, + title = {Impending arrival - a sequel to the survey on central bank digital currency}, + journal = {BIS Papers}, + volume = {107}, +} + +@article{Boneh, + author = {Boneh, Dan}, + year = {1999}, + title = {Twenty Years of Attacks on the {RSA} Cryptosystem}, + journal = {Notices of the AMS}, + volume = {42}, + number = {2}, + pages = {202--213}, +} + + +@InCollection{Bordo, + author = {Bordo, Michael D. and Andrew T. Levin}, + year = {2017}, + title = {Central bank digital currency and the future of monetary policy}, + publisher = {National Bureau of Economic Research}, + series = {NBER Working Paper Series}, + number = {23711}, +} + +@article{Brunnermeier, + author = {Brunnermeier, Markus and Dirk Niepelt}, + year = {2019}, + title = {On the Equivalence of Private and Public Money}, + journal = {Journal of Monetary Economics}, + volume = {106}, + pages = {27--41}, +} + +@article{Buiter, + author = {Buiter, Willem H. and Nikolaos Panigirtzoglou}, + year = {2003}, + title = {Overcoming the Zero Bound on Nominal Interest Rates with Negative Interest on Currency: Gesell's Solution}, + journal = {The Economic Journal}, + volume = {113}, + number = {490}, + pages = {723--746}, +} + +@InCollection{Bullmann, + author = {Bullmann, Dirk and Jonas Klemm and Andrea Pinna}, + year = {2019}, + title = {In search for stability in crypto-assets: are stablecoins the solution?}, + publisher = {European Central Bank}, + series = {ECB Occasional Paper Series}, + number = {230}, +} + +@inproceedings{Camenisch2007, + author = {Camenisch, Jan and Aanna Lysyanskaya and Mira Meyerovich}, + year = {2007}, + title = {Endorsed E-Cash}, + booktitle = {2007 IEEE Symposium on Security and Privacy (SP'07)}, + month = {May}, + pages = {101--115}, +} + +@inproceedings{Camenisch2005, + author = {Camenisch, Jan and Susan Hohenberger and Anna Lysyanskaya}, + year = {2005}, + title = {Compact E-Cash}, + booktitle = {Advances in Cryptology -- EUROCRYPT 2005: 24th Annual International Conference on the Theory and Applications of Cryptographic Techniques}, + address = {Aarhus, Denmark}, + month = {May}, + day = {22-26}, + editor = {Ed. by Ronald Cramer}, + publisher = {Springer-Verlag Berlin Heidelberg}, +} + + + +@inproceedings{Canard, + author = {Canard, Sébastien and Aline Gouget}, + year = {2007}, + title = {Divisible e-cash systems can be truly anonymous}, + booktitle = {Annual International Conference on the Theory and Applications of Cryptographic Techniques}, + pages = {482--497}, +} + + + +@misc{CCC, + author = {{CCC e.V.}}, + year = {2017}, + title = {Chaos Computer Club hacks e-motor charging stations}, + howpublished = {34c3}, +} + +@article{Chapman, + author = {Chapman, James and Rodney Garratt and Scott Hendry and Andrew McCormack and Wade McMahon}, + year = {2017}, + title = {Project {J}asper: Are Distributed Wholesale Payment Systems Feasible Yet?}, + journal = {Financial System Review}, + publisher = {Bank of Canada}, + month = {June}, + pages = {59--69}, +} + +@inproceedings{Chaum1983, + author = {Chaum, David}, + year = {1983}, + title = {Blind signatures for untraceable payments}, + booktitle = {Advances in Cryptology: Proceedings of Crypto `82}, + pages = {199--203}, +} + +@inproceedings{Chaum1990, + author = {Chaum, David and Amos Fiat and Moni Naor}, + year = {1990}, + title = {Untraceable electronic cash}, + booktitle = {Advances in Cryptology: Proceedings of CRYPTO '88}, + pages = {319--327}, +} + +@inproceedings{Danezis, + author = {Danezis, George and Sarah Meiklejohn}, + year = {2016}, + title = {Centrally Banked Cryptocurrencies}, + booktitle = {23nd Annual Network and Distributed System Security Symposium, NDSS2016}, + address = {San Diego, California, USA}, + month = {February}, + day = {21--24}, + publisher = {The Internet Society}, +} + +@article{Diffie, + author = {Diffie, Whitfield and Martin Hellmann}, + year = {1976}, + title = {New Directions in Cryptography}, + journal = {IEEE Trans. on Inf. Theory, IT-22}, + pages = {644--654}, +} + +@phdthesis{Dold, + author = {Dold, Florian}, + year = {2019}, + title = {The {GNU} {T}aler System: Practical and Provably Secure Electronic Payments. PhD Thesis}, + school = {University of Rennes 1}, +} + +@article{ECB, + author = {{European Central Bank}}, + year = {2019}, + title = {Exploring anonymity in central bank digital currencies}, + journal = {In Focus}, + number = {4}, + month = {December}, +} + +@inproceedings{Fuchsbauer, + author = {Fuchsbauer, Georg and David Pointcheval and Damien Vergnaud}, + year = {2009}, + title = {Transferable constant-size fair e-cash}, + booktitle = {International Conference on Cryptology and Network Security}, + publisher = {Springer-Verlag Berlin Heidelberg}, + pages = {226--247}, +} + +@inproceedings{Garcia, + author = {Garcia, Flavio and Gerhard de Koning Gans and Ruben Muijrers and Peter van Rossum and Roel Verdult and Ronny Wichers Schreur and Bart Jacobs}, + year = {2008}, + title = {Dismantling MIFARE Classic}, + booktitle = {European Symposium on Research in Computer Security}, +} + +@article{Garratt, + author = {Garratt, Rod and Michael Lee and Brendan Malone and Antoine Martin}, + year = {2020}, + title = {Token- or Account-Based? A Digital Currency Can Be Both}, + journal = {Liberty Street Economics}, + publisher = {Federal Reserve Bank of New York}, + month = {August}, + day = {12}, +} + +@article{Goodfriend, + author = {Goodfriend, Marvin}, + year = {2000}, + title = {Overcoming the Zero Bound on Interest Rate Policy}, + journal = {Journal of Money, Credit, and Banking}, + volume = {32}, + number = {4}, + pages = {1007--1035}, +} + +@article{Johnston, + author = {Johnston, Casey}, + year = {2010}, + title = {PS3 hacked through poor cryptography implementation}, + journal = {Ars Technica}, + month = {December}, + day = {30}, +} + + + +@Misc{Jordan, + note = {Speech given at the 30th anniversary of the WWZ and VBÖ}, + author = {Jordan, Thomas J.}, + year = {2019}, + title = {Currencies, money and digital tokens}, + publisher = {University of Basel}, + month = {September}, + howpublished = {\url{https://www.snb.ch/en/mmr/speeches/id/ref\_20190905\_tjn/source/ref\_20190905\_tjn.en.pdf}}, +} + + +@article{Kahn2009, + author = {Kahn, Charles M. and William Roberds}, + year = {2009}, + title = {Why Pay? An Introduction to Payments Economics}, + journal = {Journal of Financial Intermediation}, + number = {18}, + pages = {1--23}, +} + +@article{Kahn2005, + author = {Kahn, Charles M. and James McAndrews and William Roberds}, + year = {2005}, + title = {Money is Privacy}, + journal = {International Economic Review}, + volume = {46}, + number = {2}, + pages = {377--399}, +} + +@article{Kasper, + author = {Kasper, Timo and Michael Silbermann and Christof Paar}, + year = {2010}, + title = {All you can eat or breaking a real-world contactless payment system}, + journal = {Financial Cryptography and Data Security, Lecture Notes in Computer Science}, + volume = {6052}, + pages = {343--50}, +} + +@inproceedings{Katzenbeisser, + author = {Katzenbeisser, Stefan and Ünal Kocabaş and Vladimir Rožić and Ahmad-Reza Sadeghi and Ingrid Verbauwhede and Christian Wachsmann}, + year = {2012}, + title = {{PUF}s: Myth, Fact or Busted? A Security Evaluation of Physically Unclonable Functions ({PUF}s) Cast in Silicon}, + booktitle = {Cryptographic Hardware and Embedded Systems -- CHES 2012. Lecture Notes in Computer Science}, + volume = {7428}, + pages = {283--301}, +} + +@book{Keynes, + author = {Keynes, John Maynard}, + year = {1936}, + title = {The General Theory of Employment, Interest and Money}, + publisher = {Macmillan}, +} + +@article{Kiff, + author = {Kiff, John and Jihad Alwazir and Sonja Davidovic and Aquiles Farias and Ashraf Khan and Tanai Khiaonarong and Majid Malaika and Hunter Monroe and Nobu Sugimoto and Hervé Tourpe and Peter Zhou}, + year = {2020}, + title = {A Survey of Research on Retail Central Bank Digital Currency}, + journal = {IMF Working Paper}, + volume = {20/104}, +} + +@InCollection{Kumhof, + author = {Kumhof, Michael and Clare Noone}, + year = {2018}, + title = {Central bank digital currencies - design principles and balance sheet implications}, + publisher = {Bank of England}, + series = {Staff Working Paper}, + number = {725}, +} + +@inproceedings{Lapid, + author = {Lapid, Ben and Avishai Wool}, + year = {2018}, + title = {Cache-Attacks on the {ARM} TrustZone Implementations of {AES}-256 and {AES}-256-{GCM} via {GPU}-Based Analysis}, + booktitle = {International Conference on Selected Areas in Cryptography. Lecture Notes in Computer Science}, + volume = {11349}, +} + +@article{Lerner, + author = {Lerner, Josh and Jean Tirole}, + year = {2005}, + title = {The Scope of Open Source Licensing}, + journal = {Journal of Law, Economics \& Organization}, + volume = {21}, + pages = {20-56}, +} + +@misc{Libra, + author = {{Libra Association}}, + year = {2020}, + title = {Libra White Paper v2.0}, + url = {\url{https://libra.org/en-US/white-paper}}, +} + +@inproceedings{Lim, + author = {Lim, Chae Hoon and Phil Joong Lee}, + year = {1997}, + title = {A key recovery attack on discrete log-based schemes using a prime order subgroup}, + booktitle = {CRYPTO 1997. Lecture Notes in Computer Science}, + volume = {1294}, +} + +@InCollection{Lyons, + author = {Lyons, Richard K. and Ganesh Viswanath-Natraj}, + year = {2020}, + title = {What Keeps Stablecoins Stable?}, + publisher = {National Bureau of Economic Research}, + series = {NBER Working Paper Series}, + number = {27136}, + month = {May}, +} + +@article{Mancini-Griffoli, + author = {Mancini-Griffoli, Tommaso and Maria Soledad Martinez Peria and Itai Agur and Anil Ari and John Kiff and Adina Popescu and Celine Rochon}, + year = {2018}, + title = {Casting Light on Central Bank Digital Currency}, + journal = {IMF Staff Discussion Notes}, + volume = {18/08}, + publisher = {International Monetary Fund}, +} + +@misc{Nakamoto, + author = {Nakamoto, Satoshi}, + year = {2008}, + title = {Bitcoin: A Peer-to-Peer Electronic Cash System}, + url = {\url{https://www.bitcoin.com/bitcoin.pdf}}, +} + +@book{Narayanan, + author = {Narayanan, Arvind and Joseph Bonneau and Edward Felten and Andrew Miller and Steven Goldfeder}, + year = {2016}, + title = {Bitcoin and Cryptocurrency Technologies: A Comprehensive Introduction}, + publisher = {Princeton University Press}, +} + +@misc{Niepelt, + author = {Niepelt, Dirk}, + year = {2020}, + title = {Digital money and central bank digital currency: An executive summary for policymakers}, + url = {https://voxeu.org/article/digital-money-and-central-bank-digital-currency-executive-summary}, +} + +@inproceedings{Okamoto, + author = {Okamoto, Tatsuaki}, + year = {1995}, + title = {An Efficient Divisible Electronic Cash Scheme}, + booktitle = {Advances in Cryptology --- CRYPT0'95: 15th Annual International Cryptology Conference Santa Barbara, California, USA, August 27--31, 1995 Proceedings}, + editor = {Ed. by Don Coppersmith}, + publisher = {Springer-Verlag Berlin Heidelberg}, + pages = {438--451}, +} + +@article{Pinto, + author = {Pinto, S. and N. Santos}, + year = {2019}, + title = {Demystifying {ARM} TrustZone: A Comprehensive Survey}, + journal = {ACM Computing Surveys}, + volume = {51}, + number = {6}, + month = {January}, + pages = {1--31} +} + +@article{Rivest, + author = {Rivest, Ronald L. and Adi Shamir and Leonard Adleman}, + year = {1978}, + title = {A Method for Obtaining Digital Signatures and Public Key Cryptosystems}, + journal = {Comm. ACM}, + volume = {21}, + number = {2}, +} + +@book{Solove, + author = {Solove, Daniel J.}, + year = {2011}, + title = {Nothing to Hide: The false tradeoff between privacy and security}, + publisher = {New Haven \& London: Yale University Press}, +} + +@article{Soukup, + author = {Soukup, Michael and Bruno Muff}, + year = {2007}, + title = {Die {P}ostcard lässt sich fälschen}, + journal = {Sonntagszeitung}, + month = {April}, + day = {22}, +} + +@article{Stallman, + author = {Stallman, Richard}, + year = {1985}, + title = {The {GNU} manifesto}, + journal = {Dr. Dobb's Journal of Software Tools}, + volume = {10}, + number = {3}, + pages = {30--35}, +} + + +@TechReport{Riksbank, + author = {{Sveriges Riksbank}}, + year = {2020}, + title = {The {R}iksbank's e-krona project}, + month = {Feb}, + institution = {Sveriges Riksbank}, + url = {\url{https://www.riksbank.se/globalassets/media/rapporter/e-krona/2019/the-riksbanks-e-krona-pilot.pdf}}, +} + +@misc{Wojtczuk, + author = {Wojtczuk, Rafal and Joanna Rutkowska}, + year = {2009}, + title = {Attacking {I}ntel Trusted Execution Technology}, + howpublished = {BlackHat-DC 2009}, +} + +@article{Yalta2010, + author = {Yalta, A. Talha and A. Yasemin Yalta}, + year = {2010}, + title = {Should Economists Use Open Source Software for Doing Research?}, + journal = {Computational Economics}, + volume = {35}, + pages = {371--394}, +} + +@article{Yalta2008, + author = {Yalta, A. Talha and Riccardo Lucchetti}, + year = {2008}, + title = {The {GNU/L}inux Platform and Freedom Respecting Software for Economists}, + journal = {Journal of Applied Econometrics}, + volume = {23}, + pages = {279-286}, +} diff --git a/doc/cbdc-it/diagramma1-it.png b/doc/cbdc-it/diagramma1-it.png new file mode 100644 index 000000000..bd38d1df0 Binary files /dev/null and b/doc/cbdc-it/diagramma1-it.png differ diff --git a/doc/cbdc-it/diagramma2-it.png b/doc/cbdc-it/diagramma2-it.png new file mode 100644 index 000000000..171cb1045 Binary files /dev/null and b/doc/cbdc-it/diagramma2-it.png differ diff --git a/doc/cbdc-it/graphics-it.odp b/doc/cbdc-it/graphics-it.odp new file mode 100644 index 000000000..4c165ad5e Binary files /dev/null and b/doc/cbdc-it/graphics-it.odp differ diff --git a/doc/cs/ads/abbreviation.tex b/doc/cs/ads/abbreviation.tex new file mode 100644 index 000000000..9da168dcc --- /dev/null +++ b/doc/cs/ads/abbreviation.tex @@ -0,0 +1,48 @@ +%!TEX root = ../dokumentation.tex +\chapter*{Abbreviations} +\begin{acronym}[YTMMM] + \acro{AES}{Advanced Encryption Standard} + \acro{AML}{Anti Money Laundering} + \acro{API}{Application Programming Interface} + \acrodefplural{API}[APIs]{Application Programming Interfaces} + \acro{BIP}{Bitcoin Improvement Proposal} + \acro{CA}{Certificate Authority} + \acro{CDH}{Computational Diffie-Hellman} + \acro{CFT}{Combating Financing of Terrorism} + \acro{CMA}{Choosen-Message Attack} + \acro{CS}{Clause Blind Schnorr Signature Scheme} + \acro{CSRF}{Client-Side Request Forgery} + \acro{CWE}{Common Weakness Enumeration} + \acro{DDH}{Decisional Diffie-Hellman} + \acro{DHKE}{Diffie-Hellman key exchange} + \acro{DLP}{Discrete Logarithm Problem} + \acro{DSA}{Digital Signature Algorithm} + \acro{ECC}{Elliptic Curve Cryptography} + \acro{ECDH}{Elliptic Curve Diffie Hellman} + \acro{EdDSA}{Edwards-curve Digital Signature Algorithm} + \acro{EUF}{Existentially Unforgeability} + \acro{FDH}{Full-Domain Hash} + \acro{GNU AGPL}{GNU Affero General Public License} + \acro{GNU GPL}{GNU General Public License} + \acro{GNU LGPL}{GNU Lesser General Public License} + \acro{IPC}{Inter Process Communication} + \acro{JSON}{JavaScript Object Notation} + \acro{KDF}{Key Derivation Function} + \acro{KYC}{Know Your Customer} + \acro{MAC}{Message Authentication Code} + \acro{NIST}{National Institute of Standards and Technology} + \acro{MK}{Master Key} + \acro{PKI}{Public Key Infrastructure} + \acro{PRF}{Pseudo Random Function} + \acro{PoS}{Point-of-Sales} + \acro{PRNG}{Pseudo Random Number Generator} + \acro{RNG}{Random Number Generator} + \acro{ROS}{Random inhomogeneities in an Overdetermined, Solvable system of linear equations} + \acro{RT}{Round-Trip} + \acro{RTT}{Round-Trip Time} + \acro{SPOF}{Single Point of Failure} + \acro{SSRF}{Server-Side Request Forgery} + \acro{Taler}{GNU Taler} + \acro{TRNG}{True Random Number Generator} + \acro{URL}{uniform resource locator} +\end{acronym} diff --git a/doc/cs/ads/abstract.tex b/doc/cs/ads/abstract.tex new file mode 100644 index 000000000..0610eb10b --- /dev/null +++ b/doc/cs/ads/abstract.tex @@ -0,0 +1,26 @@ +\chapter*{Abstract} +GNU Taler is an intuitive, fast and socially responsible digital payment system implemented as free software. +While preserving the customers privacy, GNU Taler is still compliant to regulations. +\\\\ +The goal of this thesis is to improve Taler's performance and provide cipher agility by adding support for Schnorr's blind signatures. +To achieve this goal, the current state in research for Schnorr signatures needs to be analyzed. +After choosing a signature scheme, it has to be integrated into the Taler protocols. +Besides implementing the redesigned protocols in Taler, an implementation of the cryptographic routines is needed. +\\\\ +The paper "Blind Schnorr +Signatures and Signed ElGamal Encryption in the Algebraic Group Model" \cite{cryptoeprint:2019:877} from 2019 (updated in 2021) introducing \gls{CSBS} is used as theoretical basis for our improvements. +The paper explains why simple Blind Schnorr Signatures are broken and how the Clause Schnorr Blind Signature scheme is secured against this attack.\\ +Compared to the currently used \gls{RSABS}, the new scheme has an additional request, two blinding factors instead of one and many calculations are done twice to prevent attacks. +\\\\ +The Taler protocols were redesigned to support the Clause Blind Schnorr Signature scheme, including slight alterations to ensure \textit{abort-idempotency}, and then further specified. +Before starting with the implementation of the redesigned protocols, the cryptographic routines for \gls{CSBS} were implemented as part of the thesis. \\ +All of the implemented code is tested and benchmarks are added for the cryptographic routines. +\\\\ +Multiple results were achieved during this thesis: +The redesigned protocols Taler protocols with support for \gls{CSBS}, the implementation of the cryptographic routines, the implementation of Talers core protocols and a detailed comparison between \gls{RSABS} and \gls{CSBS}. +Overall, the \gls{CSBS} are significantly faster, require less disk space, and bandwidth and provide \textit{cipher agility} for Taler. + +\section*{Acknowledgement} +We would like to kindly thank Christian Grothoff (Bern University of Applied Sciences) for his extensive advice, support and very helpful feedback during our whole thesis.\\ +We also kindly thank Jeffrey Burdges (Web 3, Switzerland) for reviewing the proposal containing the redesigned protocols and giving feedback.\\ +Further, we kindly thank Jacob Appelbaum (Bern University of Applied Sciences, Eindhoven University of Technology) for further results for the performance measurements of our cryptographic routines and the insightful conversations. diff --git a/doc/cs/ads/glossary.tex b/doc/cs/ads/glossary.tex new file mode 100644 index 000000000..67ff003bc --- /dev/null +++ b/doc/cs/ads/glossary.tex @@ -0,0 +1,53 @@ +%!TEX root = ../thesis.tex + +% +% vorher in Konsole folgendes aufrufen: +% makeglossaries makeglossaries dokumentation.acn && makeglossaries dokumentation.glo +% + +% +% Glossareintraege --> referenz, name, beschreibung +% Aufruf mit \gls{...} +% +% \newglossaryentry{non-repudiation}{name={non-repudiation},plural={non-repudiation},description={After a message is signed, one can not dispute that a message was signed}} +% \newglossaryentry{sender_authenticity}{name={sender authenticity},plural={sender authenticity},description={The origin/sender of a message can not be forged}} +% \newglossaryentry{message_integrity}{name={message integrity},plural={message integrity},description={No unauthorized change to the message can be made, the message is tamperproof}} +\newglossaryentry{hkdf}{ + name = {HKDF}, + description = {The HMAC-based Extract-and-Expand Key Derivation Function is a function that takes potentially weak keying material as input and outputs high entropy keying material. For more information see section \ref{sec:kdf}} +} + +\newglossaryentry{25519}{ + name = {Curve25519}, + description = {A popular elliptic curve used in many cryptographic systems based on elliptic curve cryptography. See section \ref{par:curve25519}} +} + +\newglossaryentry{fdh}{ + name = {FDH}, + description = {A Full-Domain Hash is a hash function with an image size equal to the original gorup. See section \ref{sec:rsa-fdh}}. +} + +\newglossaryentry{idempotence}{ + name = {idempotence}, + description = {Idempotence in the context of computer science is a property to ensure that the state of system will not change, no matter how many times the same request was made. See section \ref{abort-idempotency}} +} + +\newglossaryentry{abort-idempotency}{ + name = {abort-idempotency}, + description = {Abort-idempotency is a special case of \gls{idempotence}. On every step in a protocol it needs to be ensured that even on an abort, the same request always receives the same response. See section \ref{abort-idempotency}} +} + +\newglossaryentry{RSABS}{ + name = {RSA Blind Signatures}, + description = {Chaums Blind Signature Scheme based on RSA. See section \ref{sec:blind-rsa-sign}} +} + +\newglossaryentry{CSBS}{ + name = {Clause Blind Schnorr Signatures}, + description = {A secure variant of Blind Schnorr Signature Schemes introduced in section \ref{sec:clause-blind-schnorr-sig}} +} + +% \newglossaryentry{25519}{ + % name = {}, + % description = {} +% } \ No newline at end of file diff --git a/doc/cs/ads/header.tex b/doc/cs/ads/header.tex new file mode 100644 index 000000000..0b53317b5 --- /dev/null +++ b/doc/cs/ads/header.tex @@ -0,0 +1,71 @@ +% Hyperlinks +\usepackage[ + hidelinks, + pdfusetitle, +]{hyperref} + +% Grafiken +\usepackage{graphicx} +%Bildpfad +\graphicspath{{images/}} + +% Micro sign +\usepackage{siunitx} + +% Farben +\usepackage{color} +\definecolor{LinkColor}{rgb}{0,0,0.2} + +% Glossar +\usepackage[ + nonumberlist, %keine Seitenzahlen anzeigen + %acronym, %ein Abkürzungsverzeichnis erstellen + %section, %im Inhaltsverzeichnis auf section-Ebene erscheinen + toc, %Einträge im Inhaltsverzeichnis +]{glossaries} +\makeglossaries +\input{ads/glossary} + +%Nomenklatur +\usepackage{nomencl} +\makenomenclature + +%PDF pages +\usepackage{pdfpages} + +%Adjustbox (tikz figures of Taler) +\usepackage{adjustbox} + +%BFH Boxes +% see BFH example for usage, looks nice!<< +\LoadBFHModule{listings,terminal,boxes} + +%Akronyme +\usepackage[printonlyused,footnote]{acronym} + +% Literaturverweise +\usepackage[ + backend=biber, + style=alphabetic, + %citestyle=authoryear +]{biblatex} +\addbibresource{bibliography.bib} +\addbibresource{bibliography_projekt2.bib} + +% TODOs in text +% documentation: http://tug.ctan.org/macros/latex/contrib/todonotes/todonotes.pdf +\usepackage{todonotes} + +%Crypto Grafiken +\usepackage{cryptocode} +%\usepackage{amsmath} + +\usepackage{listings} +\usepackage{xcolor} + +\definecolor{mGreen}{rgb}{0,0.6,0} +\definecolor{mGray}{rgb}{0.5,0.5,0.5} +\definecolor{mPurple}{rgb}{0.58,0,0.82} +\definecolor{backgroundColour}{rgb}{0.95,0.95,0.92} +\definecolor{ApiColor}{HTML}{307FCB} +\definecolor{whyite}{HTML}{A1C66C} % Needs to be here due to some typo in BFH-CI stuff. Thanks BFH. diff --git a/doc/cs/ads/history.tex b/doc/cs/ads/history.tex new file mode 100644 index 000000000..376ee587a --- /dev/null +++ b/doc/cs/ads/history.tex @@ -0,0 +1,12 @@ +\chapter*{Document History} +\addcontentsline{toc}{chapter}{Document History} + +%\begin{center} +\begin{tabular}{ ||l|l|l|l|| } + \hline + Version & Date & Comment & Author \\ + \hline\hline + 0.0.1 & 30.09.2021 & Document created & Gian Demarmels \& Lucien Heuzeveldt \\ + \hline +\end{tabular} +%\end{center} \ No newline at end of file diff --git a/doc/cs/bibliography.bib b/doc/cs/bibliography.bib new file mode 100644 index 000000000..014958986 --- /dev/null +++ b/doc/cs/bibliography.bib @@ -0,0 +1,362 @@ +@misc{project-definition, + author = {Dr. Emmanuel Benoist}, + title = {Adding Schnorr's blind signature in Taler}, + howpublished = {\url{https://fbi.bfh.ch/fbi/2022/Studienbetrieb/BaThesisHS21/aufgabestellungen/BIE1-1-21-en.html}}, + year = {2021} +} + +@misc{swot-analysis, + author = {Will Kenton}, + title = {Strength, Weakness, Opportunity, and Threat (SWOT) Analysis}, + year = {2021}, + howpublished = {\url{https://www.investopedia.com/terms/s/swot.asp}}, + note = {[Online; accessed 01-October-2021]} +} + + @misc{enwiki:1040250156, + author = {{Wikipedia contributors}}, + title = {Project management triangle --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + url = {https://en.wikipedia.org/w/index.php?title=Project_management_triangle&oldid=1040250156}, + note = {[Online; accessed 1-October-2021]} +} + +@misc{ionos:waterfall_model, + author = {ionos.com}, + title = {Waterfall methodology}, + year = {2019}, + url = {https://www.ionos.com/digitalguide/websites/web-development/waterfall-methodology/}, + note = {[Online; accessed 1-October-2021]} +} + +@misc{schwab:anforderungen, + author = {Gerhard Schwab}, + title = {Lerneinheit 4 - Anforderungen ermitteln}, + howpublished = {BFH Moodle}, + year = {2017} +} + +@techreport{rfc2104, + shorthand = {RFC2104}, + author = {H. Krawczyk, M.Bellare, R. Canetti}, + title = {HMAC: Keyed-Hashing for Message Authentication}, + howpublished = {Internet Requests for Comments}, + type = {RFC}, + number = 2104, + year = {1997}, + issn = {2070-1721}, + month = {02}, + publisher = {IETF}, + institution = {IETF}, + url = {https://tools.ietf.org/html/rfc2104} +} + +@techreport{rfc5869, + shorthand = {RFC5869}, + author = {H. Krawczyk, P.Eronen}, + title = {HMAC-based Extract-and-Expand Key Derivation Function (HKDF)}, + howpublished = {Internet Requests for Comments}, + type = {RFC}, + number = 5869, + year = {2010}, + issn = {2070-1721}, + month = {05}, + publisher = {IETF}, + institution = {IETF}, + url = {https://tools.ietf.org/html/rfc5869} +} + +@misc{cryptoeprint:2019:877, + author = {Georg Fuchsbauer and + Antoine Plouviez and + Yannick Seurin}, + title = {Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model}, + howpublished = {Cryptology ePrint Archive, Report 2019/877}, + year = {2019}, + note = {\url{https://ia.cr/2019/877} and \url{https://www.youtube.com/watch?v=W-uwVdGeUUs}} +} + + +@misc{bip:schnorr-bitc, + author = {Pieter Wuille, Jonas Nick, Tim Ruffing}, + title = {Schnorr Signatures for secp256k1}, + howpublished = {Bitcoin Improvement Proposal, bip-0340}, + year = {2020}, + note = {\url{https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki}} +} + +@misc{git:secp256k1-schnorr, + author = {Bitcoin Repository}, + title = {BIP-340 - Module for Schnorr signatures in libsecp256k1}, + howpublished = {\url{https://github.com/bitcoin/bitcoin/tree/master/src/secp256k1}} +} + +@misc{btc:releasnotes-0.21, + author = {Bitcoin.org }, + title = {0.21.1 Release Notes}, + howpublished = {\url{https://bitcoin.org/en/releases/0.21.1/}} +} + +@inproceedings{spring:wallet-db-with-observers, + author = {Chaum, David + and Pedersen, Torben Pryds}, + editor = {Brickell, Ernest F.}, + title = {Wallet Databases with Observers}, + booktitle = {Advances in Cryptology --- CRYPTO' 92}, + year = {1993}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {89--105}, + abstract = {Previously there have been essentially only two models for computers that people can use to handle ordinary consumer transactions: (1) the tamper-proof module, such as a smart card, that the person cannot modify or probe; and (2) the personal workstation whose inner working is totally under control of the individual. The first part of this article argues that a particular combination of these two kinds of mechanism can overcome the limitations of each alone, providing both security and correctness for organizations as well as privacy and even anonymity for individuals.}, + isbn = {978-3-540-48071-6} +} + +@misc{schnorr:perfect-dl-signatures, + author = {Claus Peter Schnorr}, + title = {Enhancing the Security of Perfect Blind DL-Signatures.}, + howpublished = {Universität Frankfurt}, + year = {2004}, + note = {\url{https://www.math.uni-frankfurt.de/~dmst/teaching/SS2012/Vorlesung/EBS5.pdf}} +} + +@misc{wagner:generalized-bday-prob, + author = {David Wagner}, + title = {A Generalized Birthday Problem}, + howpublished = {University of California Berkeley}, + year = {2002}, + note = {\url{https://www.iacr.org/archive/crypto2002/24420288/24420288.pdf}} +} + +@inproceedings{Schnorr01securityof, + author = {Claus Peter Schnorr}, + title = {Security of Blind Discrete Log Signatures against Interactive Attacks}, + booktitle = {ICICS 2001, LNCS 2229}, + year = {2001}, + pages = {1--12}, + publisher = {Springer-Verlag} +} + +@misc{pic:simple-diagram, + author = {GNU Taler}, + title = {Simple Taler Diagram}, + year = {[Online; accessed 2-November-2021]}, + note = {\url{https://taler.net/images/diagram-simple.png}} +} + +@misc{pic:refresh-prot, + author = {GNU Taler}, + title = {Taler Refresh protocol}, + year = {[Online; accessed 2-November-2021]}, + note = {\url{https://git.taler.net/marketing.git/plain/presentations/comprehensive/main.pdf}} +} + +@misc{pic:taler-overview, + author = {GNU Taler}, + title = {Operations}, + howpublished = {\url{https://git.taler.net/marketing.git/plain/presentations/comprehensive/operations.png}}, + year = {[Online; accessed 2-November-2021]}, +} + +@misc{pic:coin-state-machine, + author = {GNU Taler}, + howpublished = {\url{https://git.taler.net/exchange.git/tree/doc/system/taler/coin.pdf}}, + title = {Coin State Machine}, + year = {[Online; accessed 13 January 2022]} +} + +@misc{pic:deposit-state-machine, + author = {GNU Taler}, + howpublished = {\url{https://git.taler.net/exchange.git/tree/doc/system/taler/deposit.pdf}}, + title = {Deposit State Machine}, + year = {[Online; accessed 13 January 2022]} +} + +@misc{gnunet-git, + author = {GNUnet Git Repositories}, + title = {gnunet.git}, + howpublished = {\url{https://git.gnunet.org/gnunet.git/}} +} + +@misc{libsodium:finite-field-arithmetic, + author = {libsodium documentation}, + howpublished = {\url{https://doc.libsodium.org/advanced/point-arithmetic}}, + title = {Finite field arithmetic} +} + +@misc{bernlange:safecurves, + author = {Daniel J. Bernstein and Tanja Lange}, + title = {SafeCurves: choosing safe curves for elliptic-curve cryptography.}, + howpublished = {\url{https://safecurves.cr.yp.to}}, + year = {accessed 17 October 2021. } +} + +@misc{matt:unix-domain-sockets, + author = {Matt Lim}, + title = {Getting Started With Unix Domain Sockets}, + howpublished = {\url{https://medium.com/swlh/getting-started-with-unix-domain-sockets-4472c0db4eb1}}, + year = {accessed 08 January 2022. } +} + +@misc{rfc7748, + shorthand = {RFC7748}, + series = {Request for Comments}, + number = 7748, + howpublished = {RFC 7748}, + publisher = {RFC Editor}, + doi = {10.17487/RFC7748}, + url = {https://rfc-editor.org/rfc/rfc7748.txt}, + author = {Adam Langley and Mike Hamburg and Sean Turner}, + title = {{Elliptic Curves for Security}}, + pagetotal = 22, + year = 2016, + month = jan, + abstract = {This memo specifies two elliptic curves over prime fields that offer a high level of practical security in cryptographic applications, including Transport Layer Security (TLS). These curves are intended to operate at the \textasciitilde{}128-bit and \textasciitilde{}224-bit security level, respectively, and are generated deterministically based on a list of required properties.} +} + +@misc{ganapati:rsactftool, + author = {Ganapati}, + title = {RsaCtfTool}, + howpublished = {\url{https://github.com/Ganapati/RsaCtfTool}}, + year = {accessed 13 January 2022. } +} + +@misc{perez:stoprsa, + author = {Ben Perez}, + title = {Seriously, stop using RSA}, + howpublished = {\url{https://blog.trailofbits.com/2019/07/08/fuck-rsa/}}, + year = {accessed 13 January 2022. } +} + +@misc{geeks:rtt, + author = {preetikagupta8171}, + title = {What is RTT(Round Trip Time)?}, + howpublished = {\url{https://www.geeksforgeeks.org/what-is-rttround-trip-time/}}, + year = {accessed 13 January 2022. } +} + +@misc{madden:curve25519-clamping, + author = {Neil Madden}, + howpublished = {\url{https://neilmadden.blog/2020/05/28/whats-the-curve25519-clamping-all-about/}}, + title = {What’s the Curve25519 clamping all about?}, + year = {2020} +} + +@misc{bern:tweetnacl, + author = {Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen}, + title = {TweetNaCl: a crypto library in 100 tweets.}, + howpublished = {\url{https://tweetnacl.cr.yp.to/papers.html}}, + year = {17.09.2014} +} + +@misc{taler-presentation, + author = {GNU Taler}, + howpublished = {\url{https://git.taler.net/marketing.git/tree/presentations/comprehensive/main.pdf}}, + title = {GNU Taler}, + year = {2021} +} + +@misc{cryptoeprint:2020:945, + author = {Fabrice Benhamouda and + Tancrède Lepoint and + Julian Loss and + Michele Orrù and + Mariana Raykova}, + title = {On the (in)security of ROS}, + howpublished = {Cryptology ePrint Archive, Report 2020/945}, + year = {2020}, + note = {\url{https://ia.cr/2020/945}} +} + +@misc{rfc5246, + series = {Request for Comments}, + number = 5246, + howpublished = {RFC 5246}, + publisher = {RFC Editor}, + doi = {10.17487/RFC5246}, + url = {https://rfc-editor.org/rfc/rfc5246.txt}, + author = {Eric Rescorla and Tim Dierks}, + title = {{The Transport Layer Security (TLS) Protocol Version 1.2}}, + pagetotal = 104, + year = 2008, + month = aug, + abstract = {This document specifies Version 1.2 of the Transport Layer Security (TLS) protocol. The TLS protocol provides communications security over the Internet. The protocol allows client/server applications to communicate in a way that is designed to prevent eavesdropping, tampering, or message forgery. {[}STANDARDS-TRACK{]}} +} + +@misc{rfc6071, + series = {Request for Comments}, + number = 6071, + howpublished = {RFC 6071}, + publisher = {RFC Editor}, + doi = {10.17487/RFC6071}, + url = {https://rfc-editor.org/rfc/rfc6071.txt}, + author = {Sheila Frankel and Suresh Krishnan}, + title = {{IP Security (IPsec) and Internet Key Exchange (IKE) Document Roadmap}}, + pagetotal = 63, + year = 2011, + month = feb, + abstract = {Over the past few years, the number of RFCs that define and use IPsec and Internet Key Exchange (IKE) has greatly proliferated. This is complicated by the fact that these RFCs originate from numerous IETF working groups: the original IPsec WG, its various spin-offs, and other WGs that use IPsec and/or IKE to protect their protocols' traffic. This document is a snapshot of IPsec- and IKE-related RFCs. It includes a brief description of each RFC, along with background information explaining the motivation and context of IPsec's outgrowths and extensions. It obsoletes RFC 2411, the previous "IP Security Document Roadmap." The obsoleted IPsec roadmap (RFC 2411) briefly described the interrelationship of the various classes of base IPsec documents. The major focus of RFC 2411 was to specify the recommended contents of documents specifying additional encryption and authentication algorithms. This document is not an Internet Standards Track specification; it is published for informational purposes.} +} + + @misc{enwiki:1055393696, + author = {{Wikipedia contributors}}, + title = {RSA Factoring Challenge --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + howpublished = {\url{https://en.wikipedia.org/w/index.php?title=RSA_Factoring_Challenge&oldid=1055393696}}, + note = {[Online; accessed 16-January-2022]} +} + +@misc{cryptoeprint:2015:625, + author = {Mike Hamburg}, + title = {Ed448-Goldilocks, a new elliptic curve}, + howpublished = {Cryptology ePrint Archive, Report 2015/625}, + year = {2015}, + note = {\url{https://ia.cr/2015/625}}, +} + +@misc{bern:curve25519, + author = {Daniel J. Bernstein}, + title = {Curve25519: new Diffie-Hellman speed records}, + howpublished = {\url{https://cr.yp.to/ecdh/curve25519-20060209.pdf}}, + year = {02.09.2006} +} + +@misc{yuchen:idempotence, + author = {Yuchen Z.}, + title = {A Deep Dive Into Idempotence}, + year = {2021}, + howpublished = {\url{https://betterprogramming.pub/a-deep-dive-into-idempotence-1a39393df7e6}}, + note = {[Online; accessed 16-January-2022]} +} + +@misc{tibouchi:attacks-schnorr-nonce, + author = {Mehdi Tibouchi}, + title = {Attacks on Schnorr signatures with biased nonces}, + howpublished = {\url{https://ecc2017.cs.ru.nl/slides/ecc2017-tibouchi.pdf}}, + year = {13.11.2017} +} + +@article{wang:bitcoin-ecdsa-vuln, +author = {Wang, Ziyu and Yu, Hui and Zhang, Zongyang and Piao, Jiaming and Liu, Jianwei}, +year = {2019}, +month = {09}, +pages = {}, +title = {ECDSA weak randomness in Bitcoin}, +volume = {102}, +journal = {Future Generation Computer Systems}, +doi = {10.1016/j.future.2019.08.034} +} + +@misc{buchanan:ps3-ecdsa-vuln, + author = {Prof Bill Buchanan OBE}, + title = {Not Playing Randomly: The Sony PS3 and Bitcoin Crypto Hacks}, + howpublished = {\url{https://medium.com/asecuritysite-when-bob-met-alice/not-playing-randomly-the-sony-ps3-and-bitcoin-crypto-hacks-c1fe92bea9bc}}, + year = {12.11.2018} +} + +@misc{gian:nonce-sense, + author = {Gian Demarmels}, + title = {Nonce-Sense - Romhack CTF Crypto Challenge}, + howpublished = {\url{https://blog.c4pr1c0rn.ch/writeups/romhack_21/nonce_sence.html}}, + year = {2021}, + note = {[Online; accessed 19-January-2022]} +} \ No newline at end of file diff --git a/doc/cs/bibliography_projekt2.bib b/doc/cs/bibliography_projekt2.bib new file mode 100644 index 000000000..1f20b8c59 --- /dev/null +++ b/doc/cs/bibliography_projekt2.bib @@ -0,0 +1,442 @@ +% see here for standard templates: https://en.wikibooks.org/wiki/LaTeX/Bibliography_Management#Standard_templates + +@misc{chaum-grothoff-moser:issue-cdbc, + author = {Chaum David, Grothoff Christian, Moser Thomas}, + title = {How to issue a central bank digital currency}, + howpublished = {\url{https://www.snb.ch/en/mmr/papers/id/working_paper_2021_03}}, + year = {2021} +} + +@phdthesis{dold:the-gnu-taler-system, + author = {Florian Dold}, + title = {The GNU Taler System}, + howpublished ={\url{https://taler.net/papers/thesis-dold-phd-2019.pdf}}, + school = {Université de Rennes}, + year = {2019} +} + +@misc{schneier:value-privacy, + author = {Bruce Schneier}, + title = {The Value of Privacy}, + howpublished = {\url{https://www.schneier.com/blog/archives/2006/05/the_value_of_pr.html}}, + year = {2006} +} + +@misc{qualcomm:mobile-rng, + author = {Liang Kai}, + title = {Guard your data with the Qualcomm Snapdragon mobile platform}, + howpublished = {\url{https://www.qualcomm.com/media/documents/files/guard-your-data-with-the-qualcomm-snapdragon-mobile-platform.pdf}}, + year = {2019} +} + +@misc{chaum:blind-sign, + author = {Chaum David}, + title = {Blind Signatures for Untraceable Payments}, + howpublished = {\url{https://www.chaum.com/publications/Chaum-blind-signatures.PDF}}, + year = {1983} +} + +@misc{grothoff-dold:euro-bearer-online, + author = {Christian Grothoff, Florian Dold}, + title = {Why a Digital Euro should be Online-first and Bearer-based}, + howpublished = {\url{https://taler.net/papers/euro-bearer-online-2021.pdf}}, + year = {2021} +} + +@misc{website:bigcommerce-payment-fraud, + author = {BigCommerce}, + title = {Payment fraud: What is it and how it can be avoided?}, + howpublished = {\url{https://www.bigcommerce.com/ecommerce-answers/payment-fraud-what-it-and-how-it-can-be-avoided/}} +} + +@misc{nist:recommendation-for-key-management, + author = {Elaine Barker}, + title = {Recommendation for Key Management}, + howpublished = {\url{https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf}}, + year = {2020} +} + +@misc{taler:snackautomat, + author = {Berner Fachhochschule}, + title = {GNU Taler Snackautomat}, + howpublished = {\url{https://www.bfh.ch/de/forschung/referenzprojekte/gnu-taler-snackautomat/}} +} + +@book{modernCrypto, + author = {Nigel P. Smart}, + editor = {David Basin, Kenny Paterson}, + title = {Cryptography Made Simple}, + publisher = {Springer International Publishing Switzerland AG}, + year = {2016} +} + +@inbook{Crépeau2005, + author = {Cr{\'e}peau, Claude}, + title = {Cut-and-choose protocols}, + publisher = {School of Computr Science, McGill University, Montréal (QC), Canada}, + url = {http://crypto.cs.mcgill.ca/~crepeau/EoC/Cut&Choose.pdf} +} + +% author from github: https://github.com/chaos-eng/chaos-eng.github.io +@misc{chaos-engineering, + author = {chaos-eng}, + title = {PRINCIPLES OF CHAOS ENGINEERING}, + howpublished = {\url{https://principlesofchaos.org/}}, + year = {2019} +} + +@misc{businger:public-key-crytpo, + author = {Walter Businger}, + title = {Skript Public-Key Kryptographie}, + year = {2021} +} + +@misc{rutishauser:fuzzing, + author = {Dobin Rutishauser}, + title = {Fuzzing}, + howpublished = {Course material of BFH module Forensics and Code Security}, + year = {2021} +} + +@misc{codeblau:taler-audit, + author = {Code Blau GmbH}, + title = {Report for the GNU Taler security audit in Q2/Q3 2020}, + howpublished = {\url{https://taler.net/papers/codeblau-report-2020-q2.pdf}}, + year = {2020} +} + +@misc{pentest-execution-standard, + author = {The Penetration Testing Execution Standard}, + title = {Main Page}, + howpublished = {\url{http://www.pentest-standard.org/index.php/Main_Page}} +} + +@misc{owasp:top-ten, + author = {OWASP Foundation}, + title = {OWASP Top Ten}, + howpublished = {\url{https://owasp.org/www-project-top-ten/}} +} + +@misc{owasp:mobile-top-ten, + author = {OWASP Foundation}, + title = {OWASP Mobile Top 10}, + howpublished = {\url{https://owasp.org/www-project-mobile-top-10/}} +} + +@misc{owasp:api-security-project, + author = {OWASP Foundation}, + title = {OWASP API Security Project}, + howpublished = {\url{https://owasp.org/www-project-api-security/}} +} + +@misc{owasp:web-security-testing-guide, + author = {OWASP Foundation}, + title = {OWASP Web Security Testing Guide}, + howpublished = {\url{https://owasp.org/www-project-web-security-testing-guide/}} +} + +@misc{owasp:mobile-security-testing-guide, + author = {OWASP Foundation}, + title = {OWASP Mobile Security Testing Guide}, + howpublished = {\url{https://owasp.org/www-project-mobile-security-testing-guide/}} +} + +@misc{owasp:application-security-verification-standard, + author = {OWASP Foundation}, + title = {OWASP Application Security Verification Standard}, + howpublished = {\url{https://owasp.org/www-project-application-security-verification-standard/}} +} + +@misc{owasp:mobile-application-security-verification-standard, + author = {OWASP Foundation}, + title = {OWASP Mobile Application Security Verification Standard}, + howpublished = {\url{https://github.com/OWASP/owasp-masvs}} +} + +@misc{osstmm, + author = {ISECOM}, + title = {OSSTMM 3}, + howpublished = {\url{https://www.isecom.org/OSSTMM.3.pdf}} +} + +@misc{emscripten, + author = {Emscripten Contributors}, + title = {Emscripten documentation}, + howpublished = {\url{https://emscripten.org/}} +} + +@misc{emscripten:paper, + author = {Alon Zakai}, + title = {Emscripten: an LLVM-to-JavaScript compiler}, + howpublished = {\url{https://www.researchgate.net/publication/221320724_Emscripten_an_LLVM-to-JavaScript_compiler}}, + year = {2011} +} + +@misc{cwe, + author = {Common Weakness Enumeration}, + title = {CWE - Common Weakness Enumeration}, + howpublished = {\url{https://cwe.mitre.org/index.html}} +} + +@misc{cwe:toctou, + author = {Common Weakness Enumeration}, + title = {CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition}, + howpublished = {\url{https://cwe.mitre.org/data/definitions/367.html}}, + year = {2021} +} + +@misc{cwe:c-weaknesses, + author = {Common Weakness Enumeration}, + title = {CWE VIEW: Weaknesses in Software Written in C}, + howpublished = {\url{https://cwe.mitre.org/data/definitions/658.html}} +} + +% ---------- Taler documentation and repos +@misc{taler-documentation, + author = {Taler Systems SA}, + title = {GNU Taler Documentation}, + howpublished = {\url{https://docs.taler.net/}} +} + +@misc{taler-documentation:backup-synchronization, + author = {Taler Systems SA}, + title = {Backup and Synchronization Service API}, + howpublished = {\url{https://docs.taler.net/core/api-sync.html}} +} + +@misc{taler-documentation:auditor-operator-manual, + author = {Taler Systems SA}, + title = {GNU Taler Auditor Operator Manual}, + howpublished = {\url{https://docs.taler.net/taler-auditor-manual.html}} +} + +@misc{taler-documentation:exchange-operator-manual, + author = {Taler Systems SA}, + title = {GNU Taler Exchange Operator Manual}, + howpublished = {\url{https://docs.taler.net/taler-exchange-manual.html}} +} + +@misc{taler-documentation:merchant-backend-operator-manual, + author = {Taler Systems SA}, + title = {GNU Taler Merchant Backend Operator Manual}, + howpublished = {\url{https://docs.taler.net/taler-merchant-manual.html}} +} + +@misc{taler-documentation:merchant-api, + author = {Taler Systems SA}, + title = {GNU Taler Merchant API Tutorial}, + howpublished = {\url{https://docs.taler.net/taler-merchant-api-tutorial.html}} +} + +@misc{taler-documentation:back-office, + author = {Taler Systems SA}, + title = {Back-office Web service manual}, + howpublished = {\url{https://docs.taler.net/taler-backoffice-manual.html}} +} + +@misc{taler-documentation:pos-manual, + author = {Taler Systems SA}, + title = {GNU Taler Merchant POS Manual}, + howpublished = {\url{https://docs.taler.net/taler-merchant-pos-terminal.html}} +} + +@misc{taler-documentation:wallet-developer-manual, + author = {Taler Systems SA}, + title = {GNU Taler Wallet Developer Manual}, + howpublished = {\url{https://docs.taler.net/taler-wallet.html}} +} + +@misc{taler-documentation:wallet-cli-manual, + author = {Taler Systems SA}, + title = {GNU Taler Wallet CLI Manual}, + howpublished = {\url{https://docs.taler.net/taler-wallet-cli-manual.html}} +} + +@misc{taler-documentation:, + author = {Taler Systems SA}, + title = {}, + howpublished = {\url{}} +} + +@misc{taler-documentation:, + author = {Taler Systems SA}, + title = {}, + howpublished = {\url{}} +} + +@misc{taler-documentation:, + author = {Taler Systems SA}, + title = {}, + howpublished = {\url{}} +} + +% see https://git.taler.net/ + +@misc{taler-git, + author = {GNU Taler Git Repositories}, + title = {GNU Taler Git Repositories}, + howpublished = {\url{https://git.taler.net/}} +} + +@misc{taler-git:exchange, + author = {GNU Taler Git Repositories}, + title = {exchange.git}, + howpublished = {\url{https://git.taler.net/exchange.git/}} +} + +@misc{taler-git:merchant, + author = {GNU Taler Git Repositories}, + title = {merchant.git}, + howpublished = {\url{https://git.taler.net/merchant.git/}} +} + +@misc{taler-git:wallet-core, + author = {GNU Taler Git Repositories}, + title = {wallet-core.git}, + howpublished = {\url{https://git.taler.net/wallet-core.git/}} +} + +@misc{taler-git:auditor, + author = {GNU Taler Git Repositories}, + title = {auditor.git}, + howpublished = {\url{https://git.taler.net/auditor.git/}} +} + +@misc{taler-git:backoffice, + author = {GNU Taler Git Repositories}, + title = {backoffice.git}, + howpublished = {\url{https://git.taler.net/backoffice.git/}} +} + +@misc{taler-git:android, + author = {GNU Taler Git Repositories}, + title = {taler-android.git}, + howpublished = {\url{https://git.taler.net/taler-android.git}} +} + +@misc{taler-git:ios, + author = {GNU Taler Git Repositories}, + title = {taler-ios.git}, + howpublished = {\url{https://git.taler.net/taler-ios.git/}} +} + +@misc{taler-git:django-payments, + author = {GNU Taler Git Repositories}, + title = {django-payments-taler.git}, + howpublished = {\url{https://git.taler.net/django-payments-taler.git/}} +} + +@misc{taler-git:woocommerce, + author = {GNU Taler Git Repositories}, + title = {woocommerce-taler.git}, + howpublished = {\url{https://git.taler.net/woocommerce-taler.git/}} +} + +@misc{taler-git:saleor, + author = {GNU Taler Git Repositories}, + title = {saleor-frontend.git}, + howpublished = {\url{https://git.taler.net/saleor-frontend.git/}} +} + +@misc{taler-git:merchant-demos, + author = {GNU Taler Git Repositories}, + title = {taler-merchant-demos.git}, + howpublished = {\url{https://git.taler.net/taler-merchant-demos.git/}} +} + +% ---------- Wikipedia +@misc{dewiki:205456999, + author = {Wikipedia}, + title = {Know your customer --- Wikipedia{,} Die freie Enzyklopädie}, + year = {2020}, + url = {\url{https://de.wikipedia.org/w/index.php?title=Know_your_customer&oldid=205456999}}, + note = {[Online; Stand 3. April 2021]} +} + +@misc{enwiki:1013094030, + author = {{Wikipedia contributors}}, + title = {EdDSA --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + howpublished = {\url{https://en.wikipedia.org/w/index.php?title=EdDSA&oldid=1013094030}}, + note = {[Online; accessed 22-April-2021]} +} + +@misc{enwiki:1020240018, + author = {{Wikipedia contributors}}, + title = {Birthday problem --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + howpublished = {\url{https://en.wikipedia.org/w/index.php?title=Birthday_problem&oldid=1020240018}}, + note = {[Online; accessed 28-April-2021]} +} + +@misc{enwiki:1019272750, + author = {{Wikipedia contributors}}, + title = {Birthday attack --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + howpublished = {\url{https://en.wikipedia.org/w/index.php?title=Birthday_attack&oldid=1019272750}}, + note = {[Online; accessed 24-April-2021]} +} + +@misc{enwiki:blind-sign, + author = {{Wikipedia contributors}}, + title = {Blind signature --- {Wikipedia}{,} The Free Encyclopedia}, + year = {2021}, + howpublished = {\url{https://en.wikipedia.org/w/index.php?title=Blind_signature&oldid=1001105629}}, + note = {[Online; accessed 12-April-2021]} +} + +@misc{enwiki:1024158358, + author = "{Wikipedia contributors}", + title = "Scalability --- {Wikipedia}{,} The Free Encyclopedia", + year = "2021", + howpublished = "\url{https://en.wikipedia.org/w/index.php?title=Scalability&oldid=1024158358}", + note = "[Online; accessed 17-June-2021]" +} + +@misc{enwiki:1024197377, + author = "{Wikipedia contributors}", + title = "Chaos engineering --- {Wikipedia}{,} The Free Encyclopedia", + year = "2021", + howpublished = "\url{https://en.wikipedia.org/w/index.php?title=Chaos_engineering&oldid=1024197377}", + note = "[Online; accessed 17-June-2021]" +} + +@misc{enwiki:1026754635, + author = "{Wikipedia contributors}", + title = "Replay attack --- {Wikipedia}{,} The Free Encyclopedia", + year = "2021", + howpublished = "\url{https://en.wikipedia.org/w/index.php?title=Replay_attack&oldid=1026754635}", + note = "[Online; accessed 17-June-2021]" +} + +% ---------- RFCs +@misc{rfc8032, + series = {Request for Comments}, + number = 8032, + howpublished = {RFC 8032}, + publisher = {RFC Editor}, + doi = {10.17487/RFC8032}, + url = {https://rfc-editor.org/rfc/rfc8032.txt}, + author = {Simon Josefsson and Ilari Liusvaara}, + title = {{Edwards-Curve Digital Signature Algorithm (EdDSA)}}, + pagetotal = 60, + year = 2017, + month = jan, + abstract = {This document describes elliptic curve signature scheme Edwards-curve Digital Signature Algorithm (EdDSA). The algorithm is instantiated with recommended parameters for the edwards25519 and edwards448 curves. An example implementation and test vectors are provided.}, +} + +@misc{rfc6265, + series = {Request for Comments}, + number = 6265, + howpublished = {RFC 6265}, + publisher = {RFC Editor}, + doi = {10.17487/RFC6265}, + url = {https://rfc-editor.org/rfc/rfc6265.txt}, + author = {Adam Barth}, + title = {{HTTP State Management Mechanism}}, + pagetotal = 37, + year = 2011, + month = apr, + abstract = {This document defines the HTTP Cookie and Set-Cookie header fields. These header fields can be used by HTTP servers to store state (called cookies) at HTTP user agents, letting the servers maintain a stateful session over the mostly stateless HTTP protocol. Although cookies have many historical infelicities that degrade their security and privacy, the Cookie and Set-Cookie header fields are widely used on the Internet. This document obsoletes RFC 2965. {[}STANDARDS-TRACK{]}}, +} + diff --git a/doc/cs/content/1_introduction.tex b/doc/cs/content/1_introduction.tex new file mode 100644 index 000000000..1ed9e0589 --- /dev/null +++ b/doc/cs/content/1_introduction.tex @@ -0,0 +1,72 @@ +\chapter{Introduction} + +\section{Motivation} +Public key cryptography based on elliptic curves allows smaller key sizes compared to other cryptographic systems. +While still providing equivalent security, the smaller key size leads to huge performance benefits. +\\ +Blind Signatures are one of the key components upon which Taler's privacy is built upon. +Our thesis adds support for a modern cryptographic scheme called the Clause Blind Schnorr Signature scheme \cite{cryptoeprint:2019:877}.\\ +Additionally to the benefits of ellicptic curve cryptography, adding a second blind signature scheme makes Taler independent of a single cryptographic scheme and thus provides \textit{cipher agility}. + + +\section{Goals} +\label{sec:goals} +The project definition is as follows \cite{project-definition}: + +The students will implement the blind Schnorr signature inside Taler. +Taler is a system for the management of virtual money. +Taler is based on coins that need to be signed by an exchange (for instance a bank). +In the actual version of the system, coins are signed by the exchange using Schaum's bind-signature protocol. +This allows users to have signed coins, without the exchange knowing what it signed. +This step is fundamental for the privacy protection of the system. +\\The students have to insert the Schnorr blind signature algorithm inside the protocol for the creation of coins. +But they also need to change the Taler subsystems where the verification of the signature is done. +\\The actual Taler system allows people to let an exchange sign a coin for which they do not have the private key. +This is a security issue (for misuse of coins on the dark-net for instance). +An optional task for the project is to prevent a user to let an exchange sign a public key when the client does not have access to the corresponding private key. +\\Here is a list of the tasks that the students must do: +\begin{itemize} + \item Design a protocol integrating Schnorr blind signature in the creation of Taler coins. + \item Implement the protocol inside the exchange application and the wallet app. + \item Analyze the different Taler subsystems to find where the blind signature is verified. + \item Replace verification of the blind signature everywhere it occurs. + \item Compare both blind signature systems (Schaum's and Schnorr's), from the point of view of security, privacy protection, speed, \dots + \item Write tests for the written software. + \item Conduct tests for the written software. + \item Transfer the new software the Taler developers team +\end{itemize} +Here is a list of optional features: +\begin{itemize} + \item Design a protocol, such that the exchange can verify that the user knows the private key corresponding to the coin that is to be signed. + \item Implement that protocol. +\end{itemize} + +\section{Scope} +\label{sec:scope} +In scope are all necessary changes on the protocol(s) and components for the following tasks: +\begin{itemize} + \item Research the current state of Blind Schnorr Signature schemes + \item Redesign the Taler protocols to support Blind Schnorr signatures + \item Add support for a Blind Schnorr Signature Scheme in the exchange, merchant, wallet-core, wallet web-extension and optionally on the android mobile wallet + \item design and implement a protocol where the user proves to the exchange the knowledge of the coin that is to be signed (optional) +\end{itemize} + +Out of scope is production readyness of the implementation. +This is because changes in the protocos and code need to be thoroughly vetted to ensure that no weaknesses or security vulnerabilities were introduced. +Such an audit is out of scope for the thesis and is recommended to be performed in the future. +The iOS wallet will not be considered in this work. +\\ +It is not unusual that a scope changes when a project develops. +Due to different reasons, the scope needed to be shifted. +Since there are no libraries supporting \gls{CSBS}, the signature scheme has to be implemented and tested before integrating it into Taler. +While this is still reasonable to do in this project, it will affect the scope quite a bit. +The analysis of the optional goal showed, that a good solution that aligns with Taler's goals and properties needs more research and is a whole project by itself. + +Scope changes during the project: +\begin{itemize} + \item \textbf{Added:} Implement the cryptographic routines in GNUnet + \item \textbf{Removed: } design and implement a protocol where the user proves to the exchange the knowledge of the coin that is to be signed (optional) + \item \textbf{Adjusted: } Focus is on the implementation of the exchange protocols (Withdraw, Spend, Refresh and cryptographic utilities) + \item \textbf{Adjusted: } Implementation of the refresh protocol and wallet-core are nice-to-have goals + \item \textbf{Removed: } The Merchant and the android wallet implementations are out of scope +\end{itemize} \ No newline at end of file diff --git a/doc/cs/content/3_preliminaries.tex b/doc/cs/content/3_preliminaries.tex new file mode 100644 index 000000000..e63e65d33 --- /dev/null +++ b/doc/cs/content/3_preliminaries.tex @@ -0,0 +1,1467 @@ +\chapter{Preliminaries} +\label{chap:preliminaries} +\section{\acl{Taler} Overview} +\label{sec:taler-intro} +This chapter provides an high-level overview of GNU Taler with its core components. +The purpose of this chapter is to provide all the necessary details to understand this work and is not a specification nor a documentation of GNU Taler. +For more information on GNU Taler refer to \cite{dold:the-gnu-taler-system} or the GNU Taler documentation \cite{taler-documentation}. +\\ +Generally, GNU Taler is based on Chaumian e-cash \cite{chaum:blind-sign}. +The following parts discuss the different entities seen in the figure \ref{fig:simple-diagram} + +\subsection{Components} +\label{sec:taler-components} +In this section the different components are described as in \cite{dold:the-gnu-taler-system}. +\begin{figure}[htp] + \includegraphics[height=0.6\textwidth]{diagram-simple.png} + \centering + \caption{GNU Taler simple overview (source: \cite{pic:simple-diagram})} + \label{fig:simple-diagram} +\end{figure} + +\subsubsection{Exchange} +\label{sec:exchange} +The exchange is the payment service provider for financial transactions between a customer and merchant. +The exchange holds bank money as reserve for the anonymous digital coins. +\\ +Details of the exchange's functionality can be found in section 4.3 from Florian Dold's thesis \cite{dold:the-gnu-taler-system} or in the documentation \cite{taler-documentation:exchange-operator-manual}. +\\The code can be found in the exchange's git repository \cite{taler-git:exchange}. + +\subsubsection{Customer (Wallet)} +A customer holds Taler Coins in his electronic wallet. +As we see in figure \ref{fig:simple-diagram}, a customer can withdraw coins from the exchange. +These coins can then be spent with a merchant. +\\ +Details of the wallet's functionality can be found in section 4.6 from Florian Dold's thesis \cite{dold:the-gnu-taler-system} or in the documentations \cite{taler-documentation:wallet-developer-manual} \cite{taler-documentation:wallet-cli-manual}. +\\ +Git Repositories: +\begin{itemize} + \item Main repository \cite{taler-git:wallet-core} \\ + This Repository includes the wallet-core and the implementations for the web extension and CLI. + \item Android app \cite{taler-git:android} + \item iOS app \cite{taler-git:ios} +\end{itemize} + +\subsubsection{Merchant} +A merchant accepts Taler Coins in exchange for goods and services. +The merchant deposits these coins at the exchange and receives bank money in return. +\\ +Details of the wallet's functionality can be found in section 4.5 from Florian Dold's thesis \cite{dold:the-gnu-taler-system} or in the documentations: +\begin{itemize} + \item Operator manual \cite{taler-documentation:merchant-backend-operator-manual} + \item Merchant API \cite{taler-documentation:merchant-api} + \item Back-Office \cite{taler-documentation:back-office} + \item Point-of-Sales \cite{taler-documentation:pos-manual} +\end{itemize} + +\noindent Git Repositories: +\begin{itemize} + \item Backend: \cite{taler-git:merchant} + \item Backoffice: \cite{taler-git:backoffice} + \item Point-of-Sales App: \cite{taler-git:android} (part of android repo) +\end{itemize} + +\noindent Merchant Frontend Repositories: +\begin{itemize} + \item Payments with Django: \cite{taler-git:django-payments} + \item Wordpress woocommerce plugin: \cite{taler-git:woocommerce} + \item Saleor Frontend: \cite{taler-git:saleor} + \item Demo Frontends: \cite{taler-git:merchant-demos} +\end{itemize} + +\subsubsection{Auditor} +The auditors, which are typically run by financial regulators, have the purpose to monitor the behavior of the exchanges to assure that exchanges operate correctly. +\\ +Details of the auditor's functionality can be found in section 4.4 from Florian Dold's thesis \cite{dold:the-gnu-taler-system} or in the documentation \cite{taler-documentation:auditor-operator-manual}. +\\Git Repositories: +\begin{itemize} + \item Main repository \cite{taler-git:exchange} (Part of exchange repository, inside ./src/auditor and ./src/auditordb) + \item Auditor's public website \cite{taler-git:auditor} +\end{itemize} + +\subsubsection{Bank} +The banks receive wire transfer instructions from customers and exchanges. +As long as the banks can make wire transfers to each other, the Taler parties do not have to have the same bank. + +\subsection{Taler Step by Step} +\begin{figure}[htp] + \includegraphics[height=0.65\textwidth]{taler_bigger.png} + \centering + \caption{GNU Taler overview (source: \cite{pic:taler-overview})} + \label{fig:taler-overview-big} +\end{figure} +This is a high-level overview of what Taler generally does. +Many details (like privacy of the buyer, income transparency) are left out and are explained in the following sections. +We see in Figure \ref{fig:taler-overview-big} how Taler works step by step (at a high-level). +\begin{enumerate} + \item The customer decides to withdraw Taler coins. To do this, he goes to his bank and gives the order to pay the exchange. + \item The customers bank receives the customers order and makes a wire transfer to the exchanges Bank. + \item The exchange has received the money and the customer can now withdraw coins to his wallet. + \item The customer can now spend his coins at a merchant or merchants of his choice. + \item The merchant can then deposit the coins at the exchange. + \item The exchanges bank makes a wire transfer to the merchants bank. + \item The merchant has successfully received the money for the goods he sold. +\end{enumerate} + +\subsection{Protocols Overview} +This section provides a high-level overview of the different Taler protocols. +The details are here omitted and discussed later. + +\subsubsection{Refresh Protocol} +Taler has a quite interesting protocol to get change. +The purpose of the protocol is to give unlinkable change. +When a customer buys something from a merchant, in most situations he does not have the exact sum in coins. +For this reason, change is needed to provide a convenient payment system. +A coin can be partially spent. +When this happens, the exchange and the merchant know that this coin is used for that specific contract. +If the rest of this coin would be spent in future, one could link these two transactions. +Therefore, a mechanism to get unlinkable change while still preventing money laundering or tax evasion is needed. + +\subsubsection{Refund} +Taler has a built-in refund functionality. +Merchants can instruct the exchange to refund a transaction before the refund deadline. +The customer then refreshes the coin(s) in order for payments to remain unlinkable. + +\subsubsection{Payment Fees} +The exchange can charge fees for withdrawal, refreshing, deposition of coins. +These fees can depend on the denomination since different denominations can have different storage requirements. +Merchants are able to cover these costs fully or partially. +\\Exchanges are also able to aggregate wire transfers to merchants, thus reducing wire transfer fees. + +\subsubsection{Tipping} +Merchants can give customers a small tip. +This feature can be useful for different use cases, for example a merchant can give a tip when a customer participates in a survey. + +\subsubsection{Auditing} +Financial auditing is built-in to Taler in the form of auditors. +Auditors have read access to certain exchange databases. +Their task is to verify that exchange work as expected, see chapter 4.4 in Florian Dold's thesis \cite{dold:the-gnu-taler-system} for more details. +In future versions, the auditor will provide an interface that can be used by merchants to submit deposit confirmation samples. +This can be used to detect compromised signing keys or a malicious exchange. + +\subsection{Properties} +\label{sec:taler-properties} +%Alle Taler Eigenschaften die wir angreifen wollen auflisten und bezug nehmen wie diese erreicht werden +This section describes Taler's properties. + +\subsubsection{Free Software} +The core components of \acl{Taler} are under the following licenses: +\begin{itemize} + \item exchange \cite{taler-git:exchange}: \ac{GNU AGPL} + \item merchant \cite{taler-git:merchant}: + \begin{itemize} + \item backend: \ac{GNU GPL}v3+, \ac{GNU AGPL} + \item library: \ac{GNU LGPL} + \end{itemize} + \item wallet-core \cite{taler-git:wallet-core}: \ac{GNU GPL} +\end{itemize} + +\newpage + +\subsubsection{Buyer Privacy Protection} +Taler protects the privacy of buyers during the different stages in the lifetime of a coin: +\begin{enumerate} + \item Reserve: The reserve is identified by a key pair (private and public key). + This means that the exchange doesn't know the identity of the reserve account holder. + Whoever knows the private key is able to withdraw from the corresponding reserve. + \item Withdrawal: The withdrawal process is encrypted with TLS and uses a blind signature scheme. + Therefore the exchange doesn't know which customer holds which coin. + \item Payment: The complete payment process doesn't rely on any information identifying a customer. +\end{enumerate} +Beware that an anonymous bi-directional channel is assumed for communication between the customer and the merchant as well as during the retrieval of denomination key from the exchange and change for partially spent coins (between customer and exchange). + +\subsubsection{Merchant Taxability} +Merchant's incomes are transparent to auditors which makes taxation by the state possible. +\newline +A buyer could theoretically transfer the private key and signature of a coin directly to the merchant to bypass the exchange. +However, this is suboptimal for the merchant because the knowledge of the coin doesn't grant him the sole ownership. +If the customer spends the coin in another transaction before the merchant, the coin is voided before the merchant claims its value, thus rendering this form of payment unusable. +The same principle holds for change (refreshed coins) because it is linked to the original coin. +Whoever knows the private key and signature of the original coin can obtain the change and use it before the merchant. + +\subsubsection{\acl{AML} and \acl{CFT}} +Every transaction contains the cryptographic hash of the associated contract. +This enables the authorities to request the merchant to reveal the transaction details (the contract). +If the merchant isn't able to reveal the contract, in other words fails to deliver a contract with the same hash which is included in the transaction, he risks punishment or further investigation. +\\Another aspect for \ac{AML} and \ac{CFT} are \ac{KYC} checks. +\acl{KYC} checks require certain institutions to verify certain information about their business partners in order to prevent money laundering and terrorism (see \cite{dewiki:205456999}). +\\\acl{Taler} implements these \ac{KYC} checks: +\begin{itemize} + \item Exchanges know the identities of their customers. + \item Merchants might need to pre-register with exchanges (depending on the deployment scenario). +\end{itemize} + +\subsubsection{Payer Fraud Prevention} +The following definition was taken from the BigCommerce website \cite{website:bigcommerce-payment-fraud}. +\begin{center} + \textit{ + "Payment fraud is any type of false or illegal transaction completed by a cybercriminal. The perpetrator deprives the victim of funds, personal property, interest or sensitive information via the internet." + } +\end{center} +Prevention of payment fraud is a design goal for \acl{Taler}. + +\subsubsection{Minimal Information Disclosure} +\acl{Taler} aims to disclose as minimal information as possible. +This mostly concerns customers, but merchants also profit by keeping financial details hidden from competitors. + +\subsubsection{\acl{SPOF} Avoidance} +\ac{SPOF}s are fatal because a failure in this component can bring the complete system to a halt. + +\subsubsection{Offline Payment (unsupported)} +\acl{Taler} doesn't offer offline payments due to the CAP problem (see chapter "Challenges of offline payments" in \cite{grothoff-dold:euro-bearer-online}). + + +\section{Cryptographic Preliminaries} +\label{sec:crypto-preliminaries} +In this section we will cover the necessary preliminaries to understand Taler. +For this part we took most of the information from Nigel P. Smarts book Cryptography made simple \cite{modernCrypto} and from the course "Applied Cryptography" at the BFH. +The chapter includes preliminaries of the already implemented cryptographic schemes and the ones that are implemented during this work. + +\subsection{Hash Functions} +As source for this section, page 271-275 were used in \textit{Cryptography made Simple} \cite{modernCrypto}. +\label{sec:hashfunc} +In this paper a hash function is always a cryptographic hash function. +Cryptographic hash function are one-way functions $H()$, which are calculating the hash value $h$ from a message $m$ so that $ h = H(m)$. +With known input one can easily calculate the hash value. +The other way around is computationally infeasible. +\\ Cryptographic hash functions have the following properties. + +\subsubsection{(First) Preimage Resistance} +\label{sec:first-pre-resist} +It should be hard to find a message with a given hash value. +For a given output $y$ it is impossible to calculate the input $x$ such that $ h(x) = y$. +\\ This basically means, a hash function can not be inverted, not even with unlimited computing power. +Too much information is destroyed by the hash function and there are many values resulting in the same hash. + +\subsubsection{Second Preimage Resistance} +\label{sec:second-pre-resist} +Given one message, it should be hard to find another message with the same hash value. +For a given $x_1$ and $h(x_1)$ it is hard to find a $x_2$ such that $h(x_1) = h(x_2)$. + +\subsubsection{Collision Resistance} +\label{sec:col-resist} +It should be hard to find two messages with the same hash value. +It is quite obvious that collisions are existent, since there are more possible messages than hash values. +This is also known as the pigeonhole principle. +Even if there are hash collisions, it should be hard to find $x_1 \ne x_2$ such that $h(x_1) = h(x_2)$. +Due to the birthday paradoxon (a detailed description can be found under \cite{enwiki:1019272750}) it is easier to cause a collision of two arbitrary messages than of a specific message. + +\subsection{Key Derivation} +\label{sec:kdf} +A \ac{KDF} derives one or more cryptographically strong secret keys from initial keying material by using a \acl{PRF}. +Therefore, input of a \ac{KDF} is some sort of keying material (e.g. from a key exchange). +Output will be a pseudo-random bit-string, which can be used as new key material. + + +\subsubsection{\acl{PRF}} +A \ac{PRF} is a deterministic function whose output appears to be random if the input is unknown. +The output is computationally indistinguishable from a true random source. +Different PRFs exist, for example \ac{AES} or HMAC could be used as \ac{PRF}. +In the case of \gls{hkdf}, HMAC is a suitable choice as \ac{PRF}. + +\subsubsection{HMAC} +\label{sec:hmac} +A \acl{MAC} (\ac{MAC}) provides \textbf{unforgeability}, which means, only a person who knows the key $k$ can compute the MAC. +Further, a MAC protects the \textbf{message integrity}, since unauthorized changes are being detected. +Last but not least, \textbf{message authenticity} is provided too, since only a person who knows the key can compute the HMAC. +However, it does not provide non-repudation because it is a shared secret. +MACs take a message and a key as input and give the MAC tag as output. +\\One way to design such MACs is by using a hash function. +The obvious way one would design such a function would most likely be: $ t = H(k || m || pad)$ +However, this variant would be \textbf{completely insecure} with hash functions based on Merkle-Damgard constructions. +Because of the structure of such hash functions, it is easy to find $H(M || X)$ for an arbitrary $X$ and a hash value $H(M)$, with that a so called \textit{length-extension} attack is possible. +\\HMAC prevents this attack by computing the MAC as follows: $t = $ HMAC$_k(m) = H( (k \oplus opad) || H( (k \oplus ipad) || m) ) $ +\\ H() could be any standard hash functions, for example SHA-256, SHA-512 or SHA-3. +$\oplus$ stands for the XOR operation. +HMAC is specified in \cite{rfc2104}. + +\subsubsection{HKDF} +\gls{hkdf} follows the \textit{extract-then-expand} paradigm and therefore has two phases. +In the extract phase, the input keying material is taken and a fixed-length pseudorandom key $K$ is \textit{extracted}. +This phase is used to generate a high entropy pseudorandom key from potentially weaker input keying material. +This key $K$ is used in the \textit{expand} phase to output a variable-length, pseudorandom key. + +The \gls{hkdf} makes use of HMAC (\ref{sec:hmac}) instantiated with a hashfunction \ref{sec:hashfunc}. +It takes the input keying material, a salt and the length of output keying material as arguments. +\gls{hkdf} is specified in \cite{rfc5869}. + +\subsection{Digital Signatures} +\label{sec:sign-schemes} +As source for this section, page 216-218 were used in \textit{Cryptography made Simple}\cite{modernCrypto}. +A digital signature is a cryptographic function used to verify the origin and integrity of a message. +It provides the following properties: +\begin{itemize} + \item Sender authenticity: The origin/sender of a message can not be forged. + \item Message integrity: No unauthorized change to the message can be made, the message is tamperproof. + \item Non-repudiation: After a message is signed, one can not dispute that a message was signed. +\end{itemize} +If verification is successful, only Alice knows her private key and Bob uses Alice's public key to verify, then Bob knows that this message is really from Alice and the message has not been tampered or further modified. +A digital signature scheme has a message space M, a signature space S and three algorithms: +\begin{itemize} + \item Key generation: $(pk,sk) \gets keyGen()$ + \item Signatue generation: $s \gets $sign$_sk(m)$ + \item Verification: $ v \gets $verify$_pk(m,s)$ where $v \in {0,1}$ +\end{itemize} +If the result of the verification algorithm equals 1, a signature for m is called valid. +\\Digital signatures are publicly verifiable, which means anyone can verify that $(m,s)$ is legitimate. + +\subsubsection{Adversary Models \& Provable Security} +\label{sec:euf-cma} +Digital Signature schemes are believed to be secure when they are EUF-CMA secure. +\acl{EUF} (\ac{EUF}) means that given a public key $pk$ the adversary cannot construct a message with a valid signature, except with a negligible probability. +\acl{CMA} (\ac{CMA}) means that an adversary can ask a signing oracle to produce valid signatures $s' = sign_{sk}(m')$ for arbitrary messages $m' \ne m$.\\ +EUF-CMA is therefore existentially unforgeability under chosen message attack and is a standard security model for digital signatures. +More details can be found in page 217-218 in \textit{Cryptography made Simple} \cite{modernCrypto}. + + +\subsubsection{RSA-FDH Signature Scheme} +As source for this section, pages 300-301 and 333-335 were used in \textit{Cryptography made Simple} \cite{modernCrypto}. + +\label{sec:rsa-fdh} +RSA-FDH is a deterministic digital signature scheme which provides authenticity, message integrity and non-repudation. +The RSA signature scheme (without the full domain hash) is NOT \ac{EUF} secure and is vulnerable to existential forgery attacks. +RSA-FDH is one possible solution for a EUF-CMA secure scheme. EUF-CMA and its adversary model is further discussed in section \ref{sec:euf-cma}. +RSA-FDH is EUF-CMA secure under factoring and RSA assumptions. +More details on the hardness assumptions can be found on page 32-49 in \textit{Cryptography made Simple} \cite{modernCrypto}. + +\paragraph{\acl{FDH}} +A \acl{FDH} is a hash function with an \textbf{image size equal to the size of the RSA modulus}. +The hashfunction $h()$ used in the RSA-FDH sign (section \ref{sec:rsa-fdh-sign}) and RSA-FDH verify (section \ref{sec:rsa-fdh-sign}) needs to fulfill all the security properties we defined in chapter \ref{sec:hashfunc}. +This means that the image is a co-domain of the RSA group $\mathbb{Z}_N^*$. +Provided that the hashfunction has properties of a random oracle, \textbf{RSA-FDH is provably EUF-CMA secure} under the RSA assumption. + +\paragraph{RSA Key Generation} +\label{sec:rsa-keygen} +The information in this section is from the script of the BFH module \textit{Public Key Cryptography} taught by Prof. Dr. Walter Businger (\cite{businger:public-key-crytpo}). +The RSA private and public key are generated like this: +\begin{enumerate} + \item Generate two random prime numbers $ p, q $ where $ p \neq q $ + \item Calculate $ N = pq $ + \item Calculate $ \lambda = \text{lcm}(p-1, q-1) $ + \item Randomly choose a number $ d $ which is bigger than $ p $ and $ q $ and where $ \text{gcd}(d, \lambda) = 1 $ + \item Calculate $ e $, the multiplicative inverse of $ d \mod \lambda $ + \item The public key is $ (e, N) $, the private key is $ (d, N) $ + \item Destroy all numbers not included in the private or public key +\end{enumerate} +Note that "lcm" stands for least common multiplier and "gcd" means greatest common divisor. +The original RSA specification uses $ \phi(n) = (p-1)(q-1) $ instead of $ \lambda = \text{lcm}(p-1, q-1) $. +$ \phi(n) $ is a multiple of $ \lambda $ (for details see \cite{businger:public-key-crytpo}). + +\paragraph{Signature Algorithm} +\label{sec:rsa-fdh-sign} +The signature can be calculated as following: +\\ $ s \gets (\text{FDH}(m))^d \mod N$ + +\paragraph{Verification Algorithm} +\label{sec:rsa-fdh-verify} +The signature can be validated as following: +\\ $ \text{FDH}(m) \gets s^e \mod N$ + +\subsubsection{Schnorr Signature Scheme} +\label{sec:schnorr-sig} +The Schnorr Signature scheme is a randomized signature scheme, which is proven to be EUF-CMA secure under \ac{DLP}. +More information about the \ac{DLP} can be found in chapter 3 of \textit{Cryptography made Simple} \cite{modernCrypto}. +In february 2008 the patent expired and Schnorr signatures are now becoming widely deployed. (eg. EdDSA). +Schnorr signatures gained quite some attraction lately, since Bitcoin has announced to support Schnorr signatures starting from Block 709632 (see \cite{bip:schnorr-bitc}, \cite{btc:releasnotes-0.21}, and \cite{git:secp256k1-schnorr}). +As reference for the Schnorr signature scheme (and later Clause Blind Schnorr Signature Scheme) we use the paper \textit{Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model} \cite{cryptoeprint:2019:877} as general source for Schnorr related schemes. + +\paragraph{Setup} +We have a Group $\mathbb{G}$ of order $p$ and a generator $G$ of the group. +Further a Hashfunction $H: \{0,1\}* \rightarrow \mathbb{Z}_p$ is used. + +\paragraph{Key Generation} +The key generation is the same as in \ac{DSA}. +\begin{enumerate} + \item private key is a random integer $x \leftarrow random \in \mathbb{Z}_p$ + \item public key is $X \leftarrow xG$ +\end{enumerate} + +\paragraph{Sign} +The sign function takes the secret key $x$ and the message $m$ to be signed as argument. +The interactive version with a signer and a user can be seen in figure \ref{fig:schnorr-sign-protocol}. +\begin{enumerate} + \item choose $r \leftarrow random \in \mathbb{Z}_p $ + \item calculate $R := rG$ + \item $ c := H(R,m)$ + \item $s := r + cx \mod p$ + \item $\sigma := (R,s)$ + \item return $\sigma$ +\end{enumerate} + +\begin{figure} + \begin{equation*} + \begin{array}{ l c l } + % preliminaries + \text{User} & & \text{Signer} + \\ \text{knows:} & \text{public parameters:} & \text{knows:} + \\ \text{public key } X & \langle p, \mathbb{G}, G, H\rangle & \text{private signing key } x, X := xG + \\ & & n \leftarrow random \in \mathbb{Z}_p + \\ & & R := nG + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{R} & + \\ c := H(R,m) + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{c} & + \\ & & s := n+cx \mod p + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{s} & + \\ \text{check } sG = R + cX + \\ \sigma := \langle R,s \rangle + \end{array} + \end{equation*} + \caption{Schnorr signature protocol with user who wants to sign a message $m$ by the signer} + \label{fig:schnorr-sign-protocol} +\end{figure} + + +\paragraph{Verify} +The verify function takes the public key $X$, the message $m$ and the signature $\sigma$ as argument. +\begin{enumerate} + \item $ c := H(R,m)$ + \item check $sG = R + cX$ + \item return true if check was successful, false otherwise +\end{enumerate} + +The verification holds because $sG = R + cX $ is $ (r + cx)G = rG + cxG$ which is equal. + +\subsubsection{\acl{EdDSA}} +\ac{EdDSA} is a scheme for digital signatures based on twisted Edwards curves and the Schnorr signature scheme. +The information described here originates from \cite{rfc8032} and \cite{enwiki:1013094030}. +\ac{EdDSA} is a general algorithm that can be used with different curves. A choice in curves consists of 11 parameters. These are the most important (the others can be found in \cite{rfc8032}: +\begin{itemize} + \item odd prime power q (used to generate elliptic curve over finite field $ \mathbb{F}_q $) + \item integer b, where $ 2^{b-1} > q $, describing the bit size of various elements + \item cryptographic hash function $ H $ with output size of $ 2b $ + \item base point on curve $ B $ (generator) + \item number $ c $, (either 2 or 3) + \item prime number L where $ LB = 0 $ and $2^c*L = \text{number of points on the curve} $ +\end{itemize} + +\paragraph{Key Creation} +\label{sec:eddsa-keygen} +The private key $ k $ is a random bit-string of length $ b $. +The public key $ A $ is a point on the curve. +To generate it, we calculate $ A = sB $ where $ s = H(k)[:b] $ (meaning that we take the $ b $ least significant bits from the output of the hash function as $ s $). + +\paragraph{Signature Creation} +\label{sec:eddsa-signature-creation} +An \ac{EdDSA} signature of a message $ M $ is composed of $ (R, S )$, which are generated as follows: +\begin{align*} + s & = H(k)[:b] + \\r &= H(H(k)[b + 1:2b] \text{ || } M ) + \\R &= rB + \\S &= (r + H(R || A || M) * s) \mod L +\end{align*} +Note that $ [:b] $ means taking the $ b $ least significant bits, $ [b + 1:2b] $ means taking the b most significant bits and $ R || A $ means concatenating $ R $ and $ A $. + +\paragraph{Signature Verification} +$ (R, S) $ is the signature, $ M $ is the message, $ A $ is the public key and $c, B $ are curve parameters. +To verify a signature, the following equation must be satisfied: +\\$ 2^cSB = 2^cR + 2^cA*H(R || A || M) $ +\\This means that verify() returns 1 if the equation holds and 0 otherwise. + +\paragraph{Ed25519} +\label{par:curve25519} +Ed25519 is an \ac{EdDSA} based signature scheme and uses \gls{25519} (see \cite{bern:curve25519}), which offers 128 security bits. +\gls{25519} gets its name from the prime $ 2^{255} - 19 $ and is designed for fast computation and to resist side channel attacks. +\\These are the most important \ac{EdDSA} parameters for Ed25519 (the others can be found in \cite{rfc8032}): +\begin{itemize} + \item $ q = 2^{255} - 19 $ + \item $ b = 256 $ + \item $ H() $: SHA-512 + \item $ B = (15112221349535400772501151409588531511454012693041857206046113283949847762202, $ + \\ $46316835694926478169428394003475163141307993866256225615783033603165251855960) $ + \item $ c = 3 $ + \item $ L = 2^{252} + 27742317777372353535851937790883648493 $ +\end{itemize} +\subsection{Blind Signature Schemes} +\label{sec:blind-sign-schemes} +\label{sec:blind-sign-perfect-blindness} +One could think of blind signatures as a message put into an envelope made of carbon paper. The signer stamps his signature on the envelope and due to the properties of a carbon paper, the message is now signed too. (the stamp "stamps" through the envelope on the message). +The client then can open the envelope, and he possesses a correctly signed message. +This is achieved by the client by blinding the message with a blinding factor before sending to the signer ("blind()" operation). +The signer signs the blinded message and returns the signature of the blinded message to the client. +The client, who possesses the blinding factor can then unblind the signature and gets a signature of the original message ("unblind()" operation). +The explanation above leads us to the additional security property of a blind signature, the \textit{blindness} of signatures. +This property requires that a signer cannot link a message/signature pair to a particular execution of the signing protocol \cite{cryptoeprint:2019:877}.\\ +A blind signature scheme is called \textit{perfectly blind} if the generated signature (\textit{unblinded} signature) is statistically independent of the interaction with the signer (\textit{blinded} signature). +Thus, blind signatures cannot be linked to the signer interaction in an information theoretic sense. \cite{schnorr:perfect-dl-signatures} \cite{spring:wallet-db-with-observers} +\subsubsection{RSA Blind Signature Scheme} +\label{sec:blind-rsa-sign} +As source for this section, the course material from "Applied Cryptography" from BFH and \cite{chaum:blind-sign} were used. +The process for receiving a valid signature from the exchange uses a blind signature scheme invented by David Chaum (\cite{chaum:blind-sign}) which is based on RSA signatures. +The process is described in figure \ref{fig:blind-sign}. +\\Note that Bob (the signer) uses a standard RSA signature and can't verify if the message from Alice is blinded. +\begin{figure}[htp] + \begin{equation*} + \begin{array}{ l c l } + \text{Alice} & & \text{Bob} + \\ \text{knows:} & & \text{knows:} + \\ \text{RSA public key } D_B = e, N & & \text{RSA keys } d_B, D_B + \\ \text{message } m & & + \\ & & + \\ \text{blind:} & & + \\ r \leftarrow random \in \mathbb{Z}_N^* & & + \\ m' = m*r^{e} \mod N & & + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{m'} & + \\ & & \text{sign:} + \\ & & s' = (m')^{d_B} \mod N + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{s'} & + \\ \text{unblind:}& & + \\ s = s'*r^{-1} & & + \end{array} + \end{equation*} + \caption{Blind signature scheme} + \label{fig:blind-sign} +\end{figure} +Mathematically a blind signature works similar to the "naive" RSA signature scheme. +We consider Alice as the party who wants to have a message $m$ blindly signed by Bob. +Bob has a public key $D_B = (e, N)$ and his corresponding private key $d_B$ known only by Bob. +Alice needs to generate a random blinding factor $r\in \mathbb{Z}_N^*$, which needs to remain secret. +Alice then calculates $m'=m*r^e \mod N$. The blinded value $m'$ will now be sent to Bob by Alice. +Bob on his side calculates now the signature as usual: $s' = m'^{d_B} \mod N$. +The signature $s' $ is sent to Alice by Bob. Alice can calculate the signature as following: \\$s = s' * r^{-1}$. +\\$s$ is a valid signature of $m$, while the signer, Bob, does not know $m$ nor $b$. +\\We now want to analyze this closer to understand why blind signatures work. +Let's look at this equation: +\\$ s' = m'^{d_B} = (m*r^e)^{d_B} = m^{d_B} * (r^e)^{d_B}$. +\\The interesting part for now is $(r^e)^{d_B}$, since this is $r^1$. +This means the signature $s'$ we got from Bob is $s' = m^{d_B} * r^1$. +Now it is quite obvious how the valid signature $s$ can be calculated by multiplying with the inverse of $r$ as in: $ s = m^{d_B} * r^1 * r^{-1} = s' * r^{-1}$. + +\paragraph{Blindness} +\label{par:prop-blindness-rsa} +\gls{RSABS} are considered \textit{perfectly blind} (see \autoref{sec:blind-rsa-sign}). +There exist multiple $\langle r, m \rangle$ pairs that matches $m'$ such that $m' = m * r^e \mod N$. +Thus, \gls{RSABS} achieves \textit{perfect blindness} which cannot be attacked by brute-force or similar attacks. +Even if a valid $\langle r, m \rangle$ pair is found, the attacker has no possibility to know if it is the correct pair without additional information. + +\paragraph{RSA Blinding Attack} +There are also some possible attacks on this scheme. +First this is subject to the RSA blinding attack. +In this attack the property is used, that the signing operation is mathematically equivalent to the encrypt operation in RSA. +The attacker has a ciphertext $c = m^d$ and he wants to break this message. +Now, the attacker uses the ciphertext $c$ as "message" in the blind signature scheme above. +\\$m'' = cr^e \mod n = (m^e \mod n) * r^e \mod n = (mr)^e \mod n$. + \\The Attacker then sends the blinded message $m''$ to the signer who blindly signs the blinded message. + \\$s' = m''^d \mod n = (mr)^{ed} \mod n = m*r \mod n$. +\\The attacker recovers the message now with $m = s'*r^{-1} \mod n$. +\\This attack could be prevented by the use of a padding scheme, however this would break RSA symmetry. +In blind signatures the RSA symmetry is needed, otherwise it would produce an incorrect value in the unblind operation. +\\Due to this issue; One should never use the same key for signing and encryption! +A version of blind signatures, RSA-FDH will be discussed, which solves this issue. \cite{enwiki:blind-sign} + +\paragraph{Low Encryption Exponent Attack} +For this attack a possibly small message $m$ and a small public key $e$ is given. +If now $c = m^e < n$, one could compute $ m = \sqrt[e]{c} $. +Similar to the RSA blinding attack, padding could solve the issue, however RSA symmetry is needed. +To overcome this issue, RSA-FDH blind signatures are introduced in the next chapter. + +\subsubsection{RSA-FDH Blind Signatures} +As source for this section, the course material from "Applied Cryptograhy" from BFH and \cite{chaum:blind-sign} were used. +\label{sec:blind-sign-fdh} +Blind signatures are discussed in \ref{sec:blind-sign-schemes}. +This version is quite similar to the blind signatures already introduced in figure \ref{fig:blind-sign}. +In addition, the \gls{fdh} introduced in section \ref{sec:rsa-fdh} is used. +The difference is that the message does not get directly blinded, it gets hashed before with a \acl{FDH}. +\\Given Alice's message $m$ and Bobs public key $D_B = (e,n)$. +As in the simple \gls{RSABS}, a random blinding factor $r\in \mathbb{Z}_N^*$ is generated. +Before the message is blinded, the \acl{FDH} $ f = \text{FDH}(m)$ is calculated, which then is blinded as in $f' = fr^e \mod n$. +Since the hash function is a \acl{FDH}, $f$ is in the RSA domain $\mathbb{Z}_N^*$. +Now proceed as in the blind signature scheme introduced in the previous section. +The blinded hash $f'$ will be transmitted to Bob who then computes the signature $s' = f'^d \mod n$ and sends $s'$ back. +Alice unblinds $s'$ and gets the valid signature $s = s'r^{-1} \mod n$. + +\begin{figure}[htptp] + \begin{equation*} + \begin{array}{ l c l } + \text{Alice} & & \text{Bob} + \\ \text{knows:} & & \text{knows:} + \\ \text{RSA public key } D_B = e, N & & \text{RSA keys } d_B, D_B + \\ \text{message } m & & + \\ & & + \\ Compute f = FDH(m) & & + \\ & & + \\ \text{blind:} & & + \\ r \leftarrow random \in \mathbb{Z}_N^* & & + \\ f' = f*r^{e} \mod N & & + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{f'} & + \\ & & \text{sign:} + \\ & & s' = (f')^{d_B} \mod N + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{s'} & + \\ \text{unblind:}& & + \\ s = s'*r^{-1} & & + \end{array} + \end{equation*} + \caption{RSA-FDH blind signatues} + \label{fig:rsa-fdh-blind-sign} +\end{figure} + +This version of blind signature is not subject to the attacks introduced in the previous section. + +\subsubsection{Blind Schnorr Signature Scheme} +\label{sec:blind-schnorr-sig} +The Blind Schnorr Signature Scheme \textbf{is considered broken} and should not be implemented. +This section is here to explain how blind Schnorr signatures generally work and should help to understand The Clause Blind Schnorr Signature Scheme \ref{sec:clause-blind-schnorr-sig}. + +For the signer the calculations are the same as in the original Schnorr Signature Scheme \ref{fig:schnorr-sign-protocol}. +The exchange chooses a random $n \leftarrow random \in \mathbb{Z}_p$ and calculates $R := nG$ as before. +In comparison to the Schnorr Signature Scheme (see section \ref{sec:schnorr-sig}) we generate two random blinding factors $\alpha, \beta \leftarrow random \in \mathbb{Z}_p$ to achieve \textit{blindness}. +The User then calculates $R' := R + \alpha G + \beta X$. +This $R'$ is then used to calculate $c' := H(R',m)$ and is blinded with $b$ as in $c := c' + \beta \mod p$. +The challenge $c$ is then blindly signed by the signer $s := n+cx \mod p$. +The User checks if the signature is valid the same way as in the original protocol. +Finally the user has to unblind $s$ as in $s' := s + \alpha \mod p$. +Now the unblinded signature is $\sigma := \langle R',s' \rangle$. +This scheme is described in figure \ref{fig:schnorr-blind-sign-scheme}. +More details can be found in the \textit{Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model} paper \cite{cryptoeprint:2019:877}. + +%The unblinded signature can be verified with $s'G = R' + c'X$, since following equation is satisfied:\\ +%$s'G = sG + \alpha G = (r + cx)G + \alpha G = R + \alpha G + \beta X + (-\beta + c)X = R' + c'X = R' + H(R',m)X$ \cite{cryptoeprint:2019:877}.\\ + +To verify the signature, the verifier has to check if the following equation holds: +\begin{align*} + s'G & = R' + c' X + \\ &= R' + H(R', m) X +\end{align*} +$ s', R' $ together form the signature, $ X $ is the public key and $ m $ is message. + +The reason why this works is that the original Schnorr signature verification algorithm remains the same in blind signatures. +\begin{align*} + sG = R + c X +\end{align*} + +By replacing $ s, R, c, $ with the values used in the blind signature scheme (as in figure \ref{fig:schnorr-blind-sign-scheme}) +\begin{align*} + \\ s &= s' - \alpha + \\ R &= R' - \alpha G - \beta X + \\ c &= c' + \beta +\end{align*} + +we receive the following equation: +\begin{align*} + sG & = R + c X + \\ (s' - \alpha)G &= R' - \alpha G - \beta X + (c' + \beta)X + \\ s'G - \alpha G &= R' - \alpha G + c' X + \\ s'G &= R' + c' X +\end{align*} + +\begin{figure}[htp] + \begin{equation*} + \begin{array}{ l c l } + % preliminaries + \text{User} & & \text{Signer} + \\ \text{knows:} & \text{public parameters:} & \text{knows:} + \\ \text{public key } X & \langle p, \mathbb{G}, G, H\rangle & \text{private signing key } x, X := xG + \\ & & r \leftarrow random \in \mathbb{Z}_p + \\ & & R := rG + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{R} & + \\ \alpha, \beta \leftarrow random \in \mathbb{Z}_p + \\ R' := R + \alpha G + \beta X + \\ c' := H(R',m) + \\ c := c' + \beta \mod p + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{c} & + \\ & & s := r+cx \mod p + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{s} & + \\ \text{check } sG = R + cX + \\ s' := s + \alpha \mod p + \\ \sigma := \langle R',s' \rangle + \end{array} + \end{equation*} + \caption{The broken Schnorr Blind Signature Scheme} + \label{fig:schnorr-blind-sign-scheme} +\end{figure} + +\paragraph{Blindness} +Blind Schnorr Signatures also achieve \textit{perfect blindness} (\autoref{sec:blind-sign-perfect-blindness}). \cite{spring:wallet-db-with-observers} \cite{cryptoeprint:2019:877} + +\paragraph{ROS Problem} +\label{par:ros-problem} +The security of Blind Schnorr Signatures relies on an additional hardness assumption, the \textit{\acl{ROS}} or ROS problem. \cite{Schnorr01securityof} +Solving the \ac{ROS} problem breaks the unforgeability property of blind Schnorr signatures by finding $l + 1$ signatures out of $l$ signing operations. +David Wagner showed in his paper that the \ac{ROS} problem can be reduced to the $(l+1)$-sum problem and therefore showed that an attack is practicable. \cite{wagner:generalized-bday-prob} +More details about \ac{ROS} and Wagner's algorithm can also be found in the paper \textit{Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model} \cite{cryptoeprint:2019:877}. +\\ +Due to the possible attack, Blind Schnorr Signatures are considered \textbf{broken} and should not be used. +The next section \ref{sec:clause-blind-schnorr-sig} introduces a modified version for which the \ac{ROS} problem is much harder to solve. +\\ +The \ac{ROS} problem is a recent research topic. +Recently a paper about the (in)security of \ac{ROS} was published. \cite{cryptoeprint:2020:945} +The scheme introduced in the next section \ref{sec:clause-blind-schnorr-sig} is considered secure in 2021. +It is important to keep in mind that the \ac{ROS} problem is much newer and there is open research done. + +\subsubsection{Clause Blind Schnorr Signature Scheme} +\label{sec:clause-blind-schnorr-sig} +The Clause Blind Schnorr Signature Scheme is a modification of the Blind Schnorr Signature Scheme for which the \ac{ROS} problem is harder to solve. +The Clause Blind Schnorr Signature Scheme does this by choosing two random values $r_0, r_1$ and calculating $R_0 := r_0G; R_1 := r_1G$. +The user generates the blinding factors twice $\alpha_0, \alpha_1, \beta_0, \beta_1 \leftarrow random \in \mathbb{Z}_p$. +The user then calculates the challenges as before $c_0' := H(R_0',m); c_0 := c_0' + \beta_0 \mod p$ and $c_1' := H(R_1',m); c_1 := c_1' + \beta_1 \mod p$. +After the signer receives the two challenges $c_0$ and $c_1$, the signer randomly chooses $b \leftarrow random \{0, 1\}$ and calculates only $s_b$ as in $s := r_b+c_bx \mod p$. +The User receives $s, b$ and can unblind the signature to receive his signature $\sigma := \langle R'_b, s'_b \rangle$. +The verification algorithm remains the same for Clause Blind Schnorr Signature Scheme. +Figure \ref{fig:clause-blind-schnorr-sign-scheme} shows the Clause Blind Schnorr Signature Scheme. +More details about the scheme can be found in the paper \textit{Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model} \cite{cryptoeprint:2019:877}. + + +\begin{figure} + \begin{equation*} + \begin{array}{ l c l } + % preliminaries + \text{User} & & \text{Signer} + \\ \text{knows:} & \text{public parameters:} & \text{knows:} + \\ \text{public key } X & \langle p, \mathbb{G}, G, H\rangle & \text{private signing key } x, X := xG + \\ & & r_0, r_1 \leftarrow random \in \mathbb{Z}_p + \\ & & R_0 := r_0G + \\ & & R_1 := r_1G + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{R_0, R_1} & + \\ \alpha_0, \alpha_1, \beta_0, \beta_1 \leftarrow random \in \mathbb{Z}_p + \\ R_0' := R_0 + \alpha_0 G + \beta_0 X + \\ R_1' := R_1 + \alpha_1 G + \beta_1 X + \\ c_0' := H(R_0',m) + \\ c_1' := H(R_1',m) + \\ c_0 := c_0' + \beta_0 \mod p + \\ c_1 := c_1' + \beta_1 \mod p + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{c_0, c_1} & + \\ & & b \leftarrow random \in \{ 0,1\} + \\ & & s := r_b+c_bx \mod p + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{b, s} & + \\ \text{check } sG = R + cX + \\ s' := s + \alpha_b \mod p + \\ \sigma := \langle R_b',s' \rangle + \end{array} + \end{equation*} + \caption{The Clause Schnorr Blind Signature Scheme} + \label{fig:clause-blind-schnorr-sign-scheme} +\end{figure} + +\paragraph{Blindness} +\label{par:prop-blindness-cs} +\gls{CSBS} also achieve \textit{perfect blindness} as in Schnorr Blind Signatures (see \autoref{sec:blind-rsa-sign}). \cite{cryptoeprint:2019:877} + + +\subsection{Diffie Hellman Key Exchange} +As source for this section, pages 383-386 were used in \textit{Cryptography made Simple} \cite{modernCrypto}. +\label{sec:preliminaries-DHKE} +The \acl{DHKE} is a well proofed and well understood key exchange mechanism. +\ac{DHKE} relies mainly on the \acl{DLP}. +\ac{DHKE} is used for key exchange in many protocols today (e.g. TLS cipher suites). + +\subsubsection{Hardness Assumptions} +\label{sec:dlp} +As already stated, the \ac{DHKE} relies on the assumption that calculating the discrete logarithm is hard. +The \ac{DLP} is in $G$, where $G$ is a finite abelian group of prime order q. +This could either be a subgroup of the multiplicative group of a finite field or the set of points on an elliptic curve over a finite field. +Given $g,h \in G$, find x such that $g^x = h$. + +Further, \ac{CDH} and \ac{DDH} are important hardness assumption, which can be reduced to the \ac{DLP}. +Hardness assumptions are introduced very briefly. +In this work we believe that these well proofed and well tested hardness assumptions hold. +(See Chapter 3.1 \textit{Cryptography made Simple} \cite{modernCrypto} for more details on DH hardness assumptions.) + +\subsubsection{Protocol} +Alice and Bob want to securely exchange a key with \ac{DHKE}. +Alice has a private key $a$ and a corresponding public key $A = g^a \mod p$. +Bob has a private key $b$ and a corresponding public key $B = g^b \mod p$. +With elliptic curves, the private key is a multiplication factor for a base point $g$ (see example on page 385 \textit{Cryptography made Simple} \cite{modernCrypto}). + +Alice now sends her public key $A$ to Bob. +Bob can then calculate $k = A^b \mod p = g^{ab} \mod p$ and sends his public key $B$ to Alice. +Alice can then calculate $k = B^a \mod p = g^{ab} \mod p$. +Both get the same key $k$ as result of the key exchange. +Note: This protocol on its own is not an authenticated key exchange, which means that Man-in-the-Middle attacks are possible. + +A different way of looking at \ac{DHKE} is by thinking of a lock which can be unlocked by two (private) keys. +If one of the two private keys are known, one could calculate $k$ on its own. +Taler's refresh protocol (see \ref{sec:refresh-protocol}) uses \ac{DHKE} in a very interesting way. + +\subsection{Cut and Choose Protocol} +\label{sec:preliminaries-cut-choose} +A good introduction to cut and choose protocols gives the Paper from Claude Crépeau (\cite{Crépeau2005} References to the important examples can be found in the paper.): +\begin{center} + \textit{ + "A cut and choose protocol is a two-party protocol in which one party tries to convince another party that some data he sent to the former was honestly constructed according to an agreed upon method. + Important examples of cut-and-choose protocols are interactive proofs, interactive arguments, zero-knowledge protocols, witness indistinguishable and witness hiding protocols for proving knowledge of a piece of information that is computationally hard to find. + Such a protocol usually carries a small probability that it is successful despite the fact that the desired property is not satisfied. + \\\dots\\ + The expression cut-and-choose was later introduced by David Chaum in analogy to a popular cake sharing problem: + Given a complete cake to be shared among two parties distrusting of each other (for reasons of serious appetite). + A fair way for them to share the cake is to have one of them cut the cake in two equals hares, and let the other one choose his favourite share. + This solution guarantes that it is in the formers best interest to cut the shares as evenly as possible." + } +\end{center} + +Talers cut and choose protocol is \textit{zero knowledge}, which means that nothing about the secret is learned. +The cut and choose protocol used in Taler is explained further when the refresh protocol is discussed (see \ref{sec:refresh-protocol}). + +\section{Taler Protocols} +In section \ref{sec:taler-intro} a brief overview of how \acl{Taler} works is given. All the relevant preliminaries are covered in section \ref{sec:crypto-preliminaries}. +In this section a closer look at the different protocols is taken. + +\subsection{Withdrawal Protocol} +\label{sec:withdrawal} +The withdrawal protocol is described in chapter 4.7.2 of \cite{dold:the-gnu-taler-system}. +Before coins can be withdrawn, the customer generates a reserve key pair $ w_s, W_p \leftarrow Ed25519.KeyGen() $. +He then transfers a certain amount of money from his bank to the exchange's bank via wire transfer. +This payment must include the reserve public key $ W_p $. +The customer will later authorize withdrawals with a signature using his private reserve key. +%The customer can then authenticate, since he is in possession of the private reserve key. +As soon as the exchange has received the payment, the withdrawal for coins with a value $ i $ can begin (described in figure \ref{fig:withdrawal-process}). + +At this stage the client knows the reserve private key and the public denomination key. +The customer can then create coins up to the amount included in the wire transfer. +The coin creation and blind signatures are described in section \ref{sec:blind-sign-fdh}. +So the client generates a planchet (an Ed25519 key pair) and blinds it. +This blinded planchet is then signed by the customers private reserve key, to prove that the customer is eligible to withdraw the coin. +The exchange who receives the blinded planchet and the signature first checks whether the signature is valid with the public reserve key sent with the wire transfer. +When successful, the exchange blindly signs the planchet, returns the signature and notes the amount withdrawn of the reserve. +The customer unblinds the signature, checks its validity and persists the coin. +The state machine of a coin can be seen in figure \ref{fig:coin:states}. + +\begin{figure}[htp] + \begin{center} + \includegraphics[scale=0.58]{coin.pdf} + \end{center} + \caption{State machine of a coin (source: \cite{pic:coin-state-machine})} + \label{fig:coin:states} +\end{figure} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p & & \text{reserve public key } W_p + \\ \text{denomination public key } D_p = e, N & & \text{denomination keys } d_s, D_p + \\ & & + \\\text{generate coin key pair:} & & + \\ c_s, C_p \leftarrow Ed25519.KeyGen() & & + \\ \text{blind:} & & + \\ r \leftarrow random \in \mathbb{Z}_N^* & & + \\ m' = \text{FDH}(N, C_p)*r^{e} \mod N & & + \\ \text{sign with reserve private key:} & & + \\ \rho_W = D_p, m' & & + \\ \sigma_W = \text{Ed25519.Sign}(w_s, \rho_W) & & + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho = W_p, \sigma_W, \rho_W} & + \\ & & \text{verify if denomination public key} + \\ & & \text{is valid} + \\ & & \text{check } \text{Ed25519.Verify}(W_p, \rho_W, \sigma_W) + \\ & & \text{decrease balance if sufficient} + \\ & & \text{sign:} + \\ & & \sigma'_c = (m')^{d_s} \mod N + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\sigma'_c} & + \\ \text{unblind:}& & + \\ \sigma_c = \sigma'_c*r^{-1} & & + \\ \text{verify signature:}& & + \\ \text{check } \sigma_c^{e} = \text{FDH}(N, C_p) & & + \\ & & + \\ \text{resulting coin: } c_s, C_p, \sigma_c, D_p & & + \end{array}$ + } + \end{equation*} + \caption{Withdrawal process} + \label{fig:withdrawal-process} +\end{figure} + +\subsubsection{Withdraw Loophole} +\label{sec:withdraw-loophole} +The withdraw loophole allows withdraw operations where owner of the resulting coins isn't the owner of the reserve that the coins where withdrawn from. +It is used for tipping (described in section \ref{sec:tipping}) and can therefore be seen as a feature. + +By misusing the withdraw loophole, untaxed and untraceable payments can be performed. +Figure \ref{fig:withdraw-loophole-exploit} explains how such a payment would work. +Note that we omitted the parts leading up to the coin creation (contract, agreement of price, number of coins and their denominations). +This is how it works on a high level: +\begin{enumerate} + \item The malicous merchant generates and blinds coins, which are then transmitted to the customer + \item The customer authorizes the withdraw from his reserve by signing the blinded coins with the private key of his reserve, thus generating withdraw confirmations. + \item The withdraw confirmations are transmitted to the exchange, which generates the signatures and returns them to the malicous merchant. + \item The malicous merchant unblinds the signatures. + He is now in possession of the coin, thus the payment is completed. +\end{enumerate} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l} + % preliminaries + \textbf{Customer} & & \textbf{malicous Merchant} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p + \\ \text{denomination public key } D_p = \langle e, N \rangle & & \text{denomination public key } D_p = \langle e, N \rangle + \\ + % generate coin + \\ & & \text{generate coin key pair:} + \\ & & c_s, C_p \leftarrow \text{Ed25519.KeyGen}() + % blind + \\ & & \text{blind:} + \\ & & r \leftarrow random \in \mathbb{Z}_N^* + \\ & & m' := \text{FDH}(N, C_p)*r^{e} \mod N + % sing with reserve sk + \\ & \xleftarrow[\rule{2cm}{0pt}]{m'} + \\ \text{sign with reserve private key:} + \\ \rho_W := \langle D_p, m' \rangle + \\ \sigma_W := \text{Ed25519.Sign}(w_s, \rho_W) + \\ & \xrightarrow[\rule{2cm}{0pt}]{ \langle W_p, \sigma_W, \rho_W \rangle } + \\ + \hline + \\ + \textbf{malicous Merchant} & & \textbf{Exchange} + \\\text{knows:} & & \text{knows:} + \\& & \text{reserve public key } W_p + \\ \text{denomination public key } D_p = \langle e, N \rangle & & \text{denomination keys } d_s, D_p + \\ + \\ & \xrightarrow[\rule{2cm}{0pt}]{ \langle W_p, \sigma_W, \rho_W \rangle } + \\ & & \langle D_p, m' \rangle := \rho_W + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & \textbf{check } \text{Ed25519.Verify}(W_p, \rho_W, \sigma_W) + \\ & & \text{decrease balance if sufficient} + \\ & & \text{sign:} + \\ & & \sigma'_c := (m')^{d_s} \mod N + \\ & \xleftarrow[\rule{2cm}{0pt}]{\sigma'_c} + \\ \text{unblind:} + \\ \sigma_c := \sigma'_c*r^{-1} + \\ \text{verify signature:} + \\ \textbf{check if } \sigma_c = \text{FDH}(N, C_p) + \\ + \\ \text{resulting coin: } \langle c_s, C_p, \sigma_c, D_p \rangle + \end{array}$ + } + \end{equation*} + \caption{Untaxed payment using the withdraw loophole} + \label{fig:withdraw-loophole-exploit} +\end{figure} + +\subsection{Payment Process} +The payment process is divided in two steps described by the spend and deposit protocols. +Details about the payment process can be found in multiple chapters in \cite{dold:the-gnu-taler-system}: +Chapter 4.7.3 describes the spend and deposit protocols. +Chapter 4.1.4 describes more general aspects as well as the contract header and deposit permission structure and details. +\\On a high level, payment works like this: +\begin{enumerate} + \item The customer submits a shopping cart (one or more items to buy) and commits his intent to buy them. + \item The merchant puts together the contract terms containing the necessary information for payment, signs it and sends both to the customer (spend protocol). + \item The customer generates a deposit permission and its signature for each coin used in the transaction (spend protocol). + \item The customer forwards the deposit permission(s) to the merchant (spend protocol). + If the deposit protocol is performed by the customer, this step can be skipped. + \item Either the customer or the merchant sends the deposit permission(s) to the exchange (deposit protocol). + \item The exchange processes the deposit permission and returns a deposition confirmation when successful (deposit protocol). + \item If the deposit protocol was performed by the customer, the deposit confirmation(s) have to be forwarded to the merchant. +\end{enumerate} + +\subsubsection{Spend Protocol} +The payment process begins when a customer submits a shopping cart (one or more items to buy) and commits his intent to buy them. +The merchant has a key pair skM, pkM of which the customer knows the public key. +% besseres Wort als commit? +Note that certain details contained in contract header or deposit permission like merchant \ac{KYC} information, deposit and refund deadlines and fees are left out. +The deposit state machine can be seen in figure \ref{fig:deposit:states}. +\begin{figure}[htp] + \begin{center} + \includegraphics[scale=0.7]{deposit.pdf} + \end{center} + \caption{State machine of a deposit (source: \cite{pic:deposit-state-machine})} + \label{fig:deposit:states} +\end{figure} + +\begin{enumerate} + \item The merchant puts together the following information (without transmitting them) and requests payment: + \begin{itemize} + \item price $ v $ + \item exchange $E_m$ (multiple possible) + \item account $A_m$ at the exchange $E_m$ + \item info (free form details containing the full contract) + \end{itemize} + \item The customer generates an Ed25519 claim key pair $ p_s, P_p $ and submits the public key to the merchant. + This key can be used by the customer to prove that he didn't copy contract terms from another customer. + \item The merchant puts together the contract terms $ \rho $ and signs it with skM, resulting in the signature $ \sigma_P$. + \\The contract terms contains: + \begin{itemize} + \item $E_m$ (exchange) + \item $A_m$ (account at exchange $E_m$) + \item pkM + \item Hash($v$, info) + \item $ P_p $ + \end{itemize} + $ \rho_P $ (contract terms), $ \sigma_P$ (contract terms signature), $ v $ (price) and info are submitted to the customer. + \item The customer does the following checks: + \begin{itemize} + \item Is the signature of the contract terms correct? + \item Is the public key referenced in the contract terms the same as the one generated in step 2? + \item Is the hash of price and info the same as the one in the contract terms? + \end{itemize} + If all checks are successful, the customer chooses one or more coins to be spent. + For each coin, a deposit permission $ \rho_{D} $ and its signature $ \sigma_{D} $ is generated. + The deposit permission contains the following information: + \begin{itemize} + \item Coin public key $ C_p $ + \item Coin denomination public key pkD + \item Coin signature $ \sigma_C $ + \item Value to be spent for this coin $f$ (greater than zero, up to the residual value of the coin) + \item Hash of the contract terms $ \rho_P $ + \item Account of merchant $A_m$ (at exchange $E_m$) + \item Merchant public key pkM + \end{itemize} + The list of deposit permissions and their signatures is transferred to the merchant who then executed the deposit protocol. + Note that the customer is also able to deposit the coins (instead of the merchant), this is used in cases where the merchant doesn't have an internet connection, but the customer does. + This can be useful in cases where the merchant becomes unresponsive. + The customer can prove that he paid in time. + \item The merchant receives the deposit permissions and signatures and uses the deposit protocol to execute the payment. +\end{enumerate} + +Before we continue with the deposit protocol, there are a few interesting details to point out (described in \cite{dold:the-gnu-taler-system} section 4.1.4): +\begin{itemize} + \item The contract terms and the deposit permission are \ac{JSON} objects. + \item The contract terms only contains a cryptographic hash of the contract. + This improves privacy since the exchange doesn't have to know the full contract details, but still makes it possible to identify the contract in case of a dispute or some form of auditing. + \item At the point where the merchant completes step three (submits the contract terms and its signature) to the customer, the customer is able to finish the transaction using the deposit protocol without interaction of the merchant. + This means that the merchant at this step must be able to fulfill the contract if the customer completes the payment process. +\end{itemize} + +\subsubsection{Deposit Protocol} +\label{sec:deposit-protocol} +As previously mentioned, both parties (customer and merchant) are able to run the deposit protocol. +In the following description, the term merchant will be used, but could be replaced by customer. +In cases where there are multiple deposit permissions (meaning that multiple coins are used to pay), the deposit protocol is run separately for each deposit permission. +\begin{enumerate} + \item The merchant submits the deposit permission and its signature to the exchange. + \item The exchange runs these checks: + \begin{itemize} + \item Is the denomination public key referenced in the deposit permission valid (issued by the exchange, lifetime between start and deposit/refresh expiration, not revoked)? + \item Is the deposit permission signature $ \sigma_{D} $ a correct signature of the deposit permission $ \rho_{D} $ with the Ed25519 coin public key $ C_p $ referenced in the deposit permission? + \item Is there a processed deposit recorded in the exchanges databases based on coin public key and contract terms hash (replay/double spending)? + If not, continue with the next check since this is correct and expected behavior. + \\If there is, does the recorded deposit permission equal the one we're currently checking? + If this is the case, further checks can be skipped and the deposit confirmation signature can be returned to the customer. + If not, the process should be terminated because there's something wrong with the transaction. + \item Is the signature of the coin valid? + \item Is $ f $ (the value to be spent) smaller or equal the residual value of the coin (check for overspending attempt)? + \end{itemize} + If all checks are successful, the exchange saves the deposit record containing the deposit permission and its signature in a database, substracts the spent value from the residual value of the coin and schedules the money transfer to the merchant's account $ A_m $ (grouping payments is done to reduce payment fees). + \\The exchange calculates a deposit confirmation signature $ \sigma_{DC} $ for the deposit permission with the exchange signing private key and returns them to the merchant. + \\This signature is also used to prove that a merchant was the first to receive payment from a certain coin. + Without this, an evil exchange could later deny confirming a payment and claim double spending. + With the signature, the merchant can prove that the payment was confirmed by the exchange, thus delegating the responsibility (and potential financial loss) for double spending detection to the exchange. + \item The merchant checks the signatures of the deposit confirmations with the exchange signing public key. +\end{enumerate} + +It may happen that a payment gets stuck as partially complete, for example when a backup of a wallet is restored and one coin or more have already been spent (\cite{dold:the-gnu-taler-system} chapter 4.1.4). +In this case, the customer can retry the payment with a different coin. +If this isn't possible, the payment can be refunded (assuming refunds were enabled for this payment). +Other scenarios were described in Dold's thesis, but dismissed due to privacy concerns. +This means that disputes have to be settled aside from Taler when a customer isn't able to fully pay and refunds are disabled. + +\subsubsection{Web Payment Scenarios} +The following methods are Taler-native methods for paying and payment validation. +They are not identity-based, meaning that they do not require a login or similar techniques. +Note that other methods could be implemented depending on the scenario. + +\begin{itemize} + \item \textbf{Resource-based web payment} (\cite{dold:the-gnu-taler-system} chapter 4.1.5): + All Taler contract terms contain a fulfillment URL. + This can either be a direct link to a digital product (like a movie, a song or a document), or to a confirmation page. + When a browser opens a fulfillment URL for a resource that hasn't yet been paid for, the merchant requests payment. + The wallet then generates and submits a claim key pair, thus claiming the contract, which then can be paid (if the user accepts the contract). + The browser can then retry to navigate to the fulfillment URL, this time submitting the contract order ID as parameter, which the merchant can check if it has been paid (and deliver the content if this is the case). + This is known as the extended fulfillment URL + \\The wallet stores fulfillment URLs and their associated contracts. + Upon receiving a payment request, the wallet searches the stored fulfillment URLs and if it found one, automatically forwards the user to the extended fulfillment URL containing the contract. + \item \textbf{Session-bound payments and sharing} (\cite{dold:the-gnu-taler-system} chapter 4.1.6): + So far, validating payment is done using the extended fulfillment URL. + The problem with this approach is that this URL can be shared, which is a problem for digital content. + To make this more difficult, the seller's website assigns the user a session ID (for example using a session cookie) and extends the extended fulfillment URL with a session signature parameter. + This parameter can be used by the merchant to check if the user paid for the resource or replayed the payment in this session. + \item \textbf{Embedded content} (\cite{dold:the-gnu-taler-system} chapter 4.1.7): + When paying to access multiple resources behind a paywall (instead of just one resource), the previously described methods do not work. + Dold's thesis suggest two methods: + \begin{enumerate} + \item A session cookie can be set by accessing the fulfillment URL. + When the browser requests a subresource, the merchant can verify the session cookie. + \item In this scenario, the fulfillment URL would show the resources behind the paywall. + Upon opening the extended fulfillment URL, the merchant's website would add an authentication token to the URLs of the subresources. + When accessing a subresource, the merchant can check the authentication tokens validity. + \end{enumerate} +\end{itemize} + +\subsection{Refresh Protocol} +\label{sec:refresh-protocol} +This section provides a description of the refresh protocol. +The technical details can be found in 4.7.4 \cite{dold:the-gnu-taler-system}. +All relevant preliminaries needed to understand the technical details were already introduced in this work. + +\subsubsection{Introduction} +A protocol to refresh coins is needed for many reasons. +One important reason is giving change. +Similar to the real world, there are often situations where one does not have the exact amount of coins. +A change protocol therefore provides a lot of convenience for the users. +Without such a mechanism it would be quite hard to use. \\ +Giving change is not trivial, since \ac{AML} and \ac{CFT} compliance still needs to hold. +On the other side, the change still needs to provide privacy for the customer. +Thus, the change must be unlinkable to the previous (or any) transaction.\\ +Complying with \ac{AML} and \ac{CFT} while preserving the customer's anonymity may sound like a contradiction at first. +However, Taler has a clever way to solve this problem with the refresh protocol. + +The general idea is that the new coin can be derived from the private key of the old coin. + +\subsubsection{DH Lock} +\ac{DHKE} was introduced in section \ref{sec:preliminaries-DHKE}. +Taler uses \ac{ECDH} as a lock with two possible keys to unlock the shared key. +To create such a lock, one creates two key pairs $C = cG$ and $T = tG$. +To unlock now means calculating $k$. +Both private keys, $c$ and $t$ are now able to calculate $k = tC = t(cG) = c(tG) = cT$ and thus can unlock the lock. +This $k$ can then be used to derive the private key of the new coin and the corresponding blinding factor. + +\subsubsection{Customer Setup} + +The customer, which holds the old partially spend coin and knows \\$C_{old} = \text{Ed25519.GetPub}(c_{old})$. + A transfer key $T = \text{Ed25519.GetPub}(t)$ is then (randomly) generated by the customer. + \\The key pairs $T = \text{Ed25519.GetPub}(t)$ and $C_{old} = \text{Ed25519.GetPub}(c_{old})$ form the lock with two keys that was introduced before. + The customer then creates $x = c_{old}, T = tC_{old}$ and derives $c_{new}$, the private key of the new coin and $b_{new}$ the blinding factor of the new key. + As usual the customer calculates the coins public key $C_{new} = \text{Ed25519.GetPub}(c_{new})$, hashes the new coin with \gls{fdh} $f_{new} = \text{FDH}(C_{new})$ and blinds the hash $f'_{new} = f_{new}b_{new}^e$. + The $f'_{new}$ is then transmitted to the exchange. + \\Figure \ref{fig:refresh-derive} shows how the new coin is derived as explained above. + + \begin{figure}[htp] + \centering + \fbox{% + \procedure[codesize=\small]{$\text{RefreshDerive}(s, \langle e,N\rangle, C_p)$}{% + t := \text{HKDF}(256, s, \text{"t"}) \\ + T := \text{Curve25519.GetPub}(t) \\ + x := \textrm{ECDH-EC}(t, C_p) \\ + r := \text{SelectSeeded}(x,\mathbb{Z}^*_N)\\ + c'_s := \text{HKDF}(256,x,"c")\\ + C'_p := \text{Ed25519.GetPub}(c'_s)\\ + \overline{m} := r^e * C'_p \mod N\\ + \pcreturn \langle t, T, x, c_s', C_p', \overline{m}\rangle + } + } + \caption[RefreshDerive algorithm]{The RefreshDerive derives a new coin from a dirty coin with a seed. The DH-Lock is used to create the link used in the linking protocol} + \label{fig:refresh-derive} + \end{figure} + + Now with the DH Lock the person who is in possession of the old key can always recalculate and thus spend the new coin (as long as it knows the public transfer key $T$). + However, there is one last thing: How does the exchange know that the old key is linked to the new one? + To comply with \ac{AML} and \ac{CFT}, the exchange wants to ensure that the person who created the new coin is also in possession of the old coin. + A link needs to be created in a way that nobody can link the old coin to the new coin, except the person in possession of the old coin. + The person in possession of the old coin needs to proof to the exchange that this link was created without revealing the link. + This problem is solved with the cut and choose protocol in the next section. + + \begin{figure}[htp] + \centering + \includegraphics[height=0.5\textwidth]{taler_refresh_transfer_key.png} + \caption{Taler refresh protocol, transfer key setup (source: \cite{pic:refresh-prot})} + \label{fig:taler-refresh-transfer-key} + \end{figure} + \newpage + \subsubsection{Cut \& Choose} + Instead of doing the customer setup once, it is done $n$ times. + The customer generates $n$ different transfer keys $t_1, t_2 \dots t_n$. + For each key the whole calculations are done and all the blinded coins $f'_1, f'_2 \dots f'_n$ are sent to the exchange together with the old coins public key and signature. \\ + The exchange responds with a randomly picked number from $1$ to $n$. + The customer has to reveal all the transfer keys, \textbf{except the one picked by the exchange.} + The exchange makes the same calculations with the revealed private transfer keys (without knowing the private key $c_{old}$). + The exchange can now verify whether the customer was honest or not. + A evil customer could create a new coin which is not linked to the old coin (without the DH lock). + Such attacks will be detected with a high probability in this protocol. + Since the $t_x$ picked by the exchange is not checked, an evil customer can win this with a probability of $1/n$. + Already with $n=3$ an attack is not in the customers interest due to economic reasons. + In 2 out of 3 cases the exchange would detect the attack and would keep the money and the customer would have lost it. + The probability can be adjusted with $n$. + With increasing size of $n$ the attack becomes even less attractive. + When the cut and choose protocol ended successfully, the value of the old coin is set to zero. + + \begin{figure}[htp] + \centering + \includegraphics[height=0.5\textwidth]{taler_cut_and_choose.png} + \caption{Taler refresh protocol, cut and choose (source: \cite{pic:refresh-prot})} + \label{fig:taler-cut-and-choose} + \end{figure} + + \subsection{Commit Phase} + \label{sec:commit-phase-rsa} + The refresh protocol is implemented in two phases. + The commit phases creates $k$ derives and commits to this values by calculating a hash over the derives. + On the exchange's side various checks are done to validate the request. + Detailed steps of the commit phase are shown in figure \ref{fig:refresh-part1}. + + + \begin{figure} + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{denomination public key } D_{p(i)} & & \text{denomination keys } d_{s(i)}, D_{p(i)} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_c^{(0)} \rangle & & + % refresh request + \\ \text{Select} \langle N_t, e_t\rangle := D_{p(t)} \in D_{p(i)} + \\ \textbf{for } i = 1, \dots, \kappa: % generate k derives + \\ s_i \rightarrow \{0,1\}^{256} % seed generation + \\ X_i := \text{RefreshDerive}(s_i, D_{p(t)}, C_p^{(0)}) + \\ (t_i, T_i, x_i, c_s^{(i)}, C_p^{(i)}, \overline{m}_i) := X_i + \\ \textbf{endfor} + \\ h_T := H(T_1, \dots, T_k) + \\ h_{\overline{m}} := H(\overline{m}_1, \dots, \overline{m}_k) + \\ h_C := H(h_t, h_{\overline{m}}) + \\ \rho_{RC} := \langle h_C, D_{p(t)}, D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} \rangle + \\ \sigma_{RC} := \text{Ed25519.Sign}(c_s^{(0), \rho_{RC}}) + \\ \text{Persist refresh-request} \langle \rho_{RC}, \sigma_{RC} \rangle + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RC}, \sigma_{RC}} & + % Exchange checks refresh request + \\ & & (h_C, D_{p(t)}, D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} = \rho_{RC}) + \\ & & \textbf{check} \text{Ed25519.Verify}(C_p^{(0)}, \sigma_{RC}, \rho_{RC}) + \\ & & x \rightarrow \text{GetOldRefresh}(\rho_{RC}) + \\ & & \textbf{Comment: }\text{GetOldRefresh} \\(\rho_{RC} \mapsto \{\bot,\gamma\}) + \\ & & \pcif x = \bot + \\ & & v := D(D_{p(t)}) + \\ & & \langle e_0, N_0 \rangle := D_{p(0)} + \\ & & \textbf{check } \text{IsOverspending}(C_p^{(0)}, D_ {p(0)}, v) + \\ & & \textbf{check } D_{p(t)} \in \{D_{p(i)}\} + \\ & & \textbf{check } \text{FDH}(N_0, C_p^{(0)}) \equiv_{N_0} (\sigma_0^{(0)})^{e_0} + \\ & & \text{MarkFractionalSpend}(C_p^{(0)}, v) + \\ & & \gamma \leftarrow \{1, \dots, \kappa\} + \\ & & \text{Persist refresh-record } \langle \rho_{RC},\gamma \rangle + \\ & & \pcelse + \\ & & \gamma := x + \\ & & \textbf{endif} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\gamma} & + \\ + \\ + \\ & \textit{Continued in figure \ref{fig:refresh-part2}} & + %\\ \pcintertext[dotted]{(Continued in Figure)} + \end{array}$ + } + \end{equation*} + \caption{Refresh protocol (commit phase)} + \label{fig:refresh-part1} + \end{figure} + + \subsection{Reveal Phase} + \label{sec:reveal-phase-rsa} + In the reveal phase the customer receives $\gamma$ and he reveals the all the seeds to the exchange, except for $s_\gamma$. + The exchange can then verify if the customer was honest with probability $1/k$. + On success the exchange will return the blinded signature of the new coin and the customer can then unblind and store the coin. + The reveal phase is described in figure \ref{fig:refresh-part2} + + \begin{figure} + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ & \textit{Continuation of figure \ref{fig:refresh-part1}} & + \\ + \\ + % Check challenge and send challenge response (reveal not selected msgs) + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\gamma} & + \\ \textbf{check } \text{IsConsistentChallenge}(\rho_{RC}, \gamma) + \\ \textbf{Comment: } \text{IsConsistentChallenge}\\(\rho_{RC}, \gamma) \mapsto \{ \bot,\top \} + \\ + \\ \text{Persist refresh-challenge} \langle \rho_{RC}, \gamma \rangle + \\ S := \langle s_1, \dots, s_{\gamma-1}, s_{\gamma+1}, \dots,s_x \rangle % all seeds without the gamma seed + \\ \rho_L = \langle C_p^{(0)}, D_{p(t)}, T_{\gamma},\overline{m}_\gamma \rangle + \\ \rho_{RR} = \langle T_\gamma, \overline{m}_\gamma, S \rangle + \\ \sigma_{L} = \text{Ed25519.Sign}(c_s^{(0)}, \rho_{L}) + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RR},\rho_L, \sigma_{L}} & + % check revealed msgs and sign coin + \\ & & \langle T'_\gamma, \overline{m}'_\gamma, S \rangle := \rho_{RR} + \\ & & \langle s_1,\dots,s_{\gamma-1},s_{\gamma+1},\dots,s_\kappa \rangle ) := S + \\ & & \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \sigma_L, \rho_L) + \\ & & \pcfor i = 1,\dots, \gamma-1, \gamma+1,\dots, \kappa + \\ & & X_i := \text{RefreshDerive}(s_i, D_{p(t)}, C_p^{(0)}) + \\ & & \langle t_i, T_i, x_i, c_s^{(i)}, C_p^{(i)}, \overline{m}_i \rangle := X_i + \\ & & \textbf{endfor} + \\ & & h_T' = H(T_1,\dots,T_{\gamma-1},T'_{\gamma},T_{\gamma+1},\dots,T_\kappa) + \\ & & h_{\overline{m}}' = H(\overline{m}_1,\dots,\overline{m}_{\gamma-1},\overline{m}'_{\gamma},\overline{m}_{\gamma+1},\dots,\overline{m}_\kappa) + \\ & & h_C' = H(h_T', h_{\overline{m}}') + \\ & & \textbf{check } h_C = h_C' + \\ & & \overline{\sigma}_C^{(\gamma)} := \overline{m}^{d_{s(t)}} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\overline{\sigma}_C^{(\gamma)}} & + % Check coin signature and persist coin + \\ \sigma_C^{(\gamma)} := r^{-1}\overline{\sigma}_C^{(\gamma)} + \\ \textbf{check } (\sigma_C^{(\gamma)})^{e_t} \equiv_{N_t} C_p^{(\gamma)} + \\ \text{Persist coin} \langle D_{p(t)}, c_s^{(\gamma)}, C_p^{(\gamma)}, \sigma_C^{(\gamma)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Refresh protocol (reveal phase)} + \label{fig:refresh-part2} + \end{figure} + + \subsubsection{(Un)linkability} + \begin{figure}[htp] + \centering + \includegraphics[height=0.5\textwidth]{taler_refresh_link_threat.png} + \caption{Taler refresh protocol, linkability (source: \cite{pic:refresh-prot})} + \label{fig:taler-link-threat} + \end{figure} + The goal of the cut and choose protocol is to ensure with a high probability ($1/n$) that the customer honestly created the new coin. + It ensures that the old coin is linked to the new coin via the DH lock. + + With that, the following attack scenario is prevented (with probability $1/n$):\\ + An third party creates the new coin without the DH lock as described in section \ref{sec:blind-sign-schemes}. + The third party sends the blinded new coin to the customer (who possesses the old coin). + The customer then signs the new coin by the exchange and sends the blinded signature back to the third party. + The third party would then be in possession of a valid new coin, which is not linked to the old coin. + As mentioned, such an attack is detected with a high probability by the exchange with the cut and choose protocol described earlier. + + We will now consider the following attack scenario:\\ + Someone could give the private key of the old coin $c_{old}$ to another person. + This other person then can derive a new coin using the refresh protocol. + The original customer currently can not recreate the new coin with only the knowledge of the old coins private key $c_{old}$. + He would need to know the public key of the transfer key $T_x$ and also the blinded signature of the new coin $f'_{new}$. + For this reason the exchange exposes the public transfer key $T_x$ and the blinded new coin $f'_{new}$ for a given old coin $C_{old}$. + So anybody who knows the public key of the old coin could ask for the public transfer key and the blinded signature of the new coin. + Only a person in possession of the old coins private key $c_{old}$ can recreate the new coin's private key. \\ +This mechanism can not be abused for money laundering anymore, since the original customer could trick this third person and spend the coin faster. +The linking protocol is described in figure \ref{fig:refresh-link}. + +\begin{figure} + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_{C}^{(0)} \rangle + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{C_{p(0)}} & + \\ & & L := \text{LookupLink}(C_{p(0)}) + \\ & & \textbf{Comment: } \text{LookupLink}(C_p) \mapsto \{\langle \rho_L^{(i)}, + \\ & & \sigma_L^{(i)}, \overline{\sigma}_C^{(i)} \rangle\} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{L} & + \\ \pcfor \langle \rho_{L}^{(i)}, \overline{\sigma}_L^{(i)}, \sigma_C^{(i)} \rangle \in L + \\ \langle \hat{C}_p^{(i)}, D_{p(t)}^{(i)}, T_\gamma^{(i)}, \overline{m}_\gamma^{(i)} \rangle := \rho_L^{(i)} + \\ \langle e_t^{(i)}, N_t^{(i)} \rangle := D_{p(t)}^{(i)} + \\ \textbf{check } \hat{C}_p^{(i)} \equiv C_p^{(0)} + \\ \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \rho_{L}^{(i)}, \sigma_L^{(i)}) + \\ x_i := \text{ECDH}(c_s^{(0)}, T_{\gamma}^{(i)}) + \\ r_i := \text{SelectSeeded}(x_i,\mathbb{Z}^*_{N_t}) + \\ c_s^{(i)} := \text{HKDF}(256,x_i,"c") + \\ C_p^{(i)} := \text{Ed25519.GetPub}(c_s^{(i)}) + \\ \sigma_C^{(i)} := (r_i)^{-1} \cdot \overline{m}_\gamma^{(i)} + \\ \textbf{check } (\sigma_C^{(i)})^{e_t^{(i)}} \equiv_{N_t^{(i)}} C_p^{(i)} + \\ \text{(Re-)obtain coin} \langle D_{p(t)}^{(i)},c_s^{(i)}, C_p^{(i)}, \sigma_C^{(i)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Linking protocol} + \label{fig:refresh-link} +\end{figure} + + +\subsection{Tipping Protocol} +\label{sec:tipping} +Source for this protocol was section 4.1.10 from \cite{dold:the-gnu-taler-system}.\\ +Merchants can give customers a small tip by using the withdraw loophole (described in section \ref{sec:withdraw-loophole}). +This can be for a variety of different reasons, for example for submitting a survey. +The merchant needs to create a reserve with the exchange. +The reserve keys is now used to sign blinded coins generated by the user. +\begin{enumerate} + \item The Merchant triggers the Payment required response with the Taler-Tip header set + \item The taler tip header contains information like amount, exchange to use, deadline and more. (details section 4.1.10 \cite{dold:the-gnu-taler-system}) + \item The customer creates planchets that sum up the amount and blinds the token with the denomination key of the specified exchange and sends the blinded planchets to the merchant. + \item The merchant creates withdrawal confirmations (by signing them with the reserver private key) for these planchets and responds with a list of signatures. + \item The customer then uses these signatures to create coins as in the withdrawal protocol +\end{enumerate} +The received coins are still anonymized and only spendable by the customer. + + +\subsection{Refund Protocol} +A merchant can undo a deposit on a coin by signing a refund permission. +The protocol details can be found in section 4.7.5 of \cite{dold:the-gnu-taler-system}. +Since a refund is mainly done by the merchant, to provide refunds a merchant need to support refunds. +A refund can be either fully or partially. +After a refund, the customer is able to spend the coin, but it should be refreshed first to prevent linking of transactions. +The refund deadline is specified in the contract header, after the deadline the exchange makes a wire transfer with the money to the merchants bank. +There is a refund fee, which is subtracted from the remaining coin value. +This also prevents denial of service attacks, or at least makes them economically uninteresting. +There exists automatic refunds when a payment only partially succeeds for many reasons. +Refunds are also an important business case for many merchants who want to provide a convenient experience. +A merchant can for example provide a refund when the customer is not happy with the product. +Such a refund can be made by the merchant with a signature without the customers consent. +Now should be clear what the purpose of a refund protocol is, the rest of this section will look at the refund protocol. + + +In the protocol the customer requests a refund from the merchant. +If the merchant accepts the request, it authorizes the exchange to apply the refund. +\begin{enumerate} + \item The customer asks for a refund for payment $p$ with reason $m$ + \item The merchant decides whether it accepts the refund or not according to the merchants business rules. + \item If accepted, the merchant signs the refund permission with the merchants Ed25519 key and sends it to exchange. + \item The exchange checks the signature and refunds the coin(s) and sends a signed confirmation to the merchant. + \item The merchant sends the signed confirmation from the exchange to the customer. +\end{enumerate} + +\section{Trust and PKI in Taler} +In this section Taler's \ac{PKI} is explained and how Taler handles trust. +This section is included due to the reason that we have to create Schnorr denomination keys to add the Clause Blind Schnorr Signature scheme to Taler. +Taler uses TLS, however it does not rely on TLS for authenticity or integrity. (More detailed in chapter 4.1.3 of \cite{dold:the-gnu-taler-system}) + +\subsubsection{Auditor} +In Taler the auditors serves as trust anchor, and they are identified by a single Ed25519 public key. +Similar to the list of trusted root \ac{CA} that come with web browsers and operating systems, a wallet comes with a list of trusted auditor certificates. +In the rest of this section, different parts of Taler and how they are integrated in Taler's \ac{PKI} are discussed. +The section ends with a discussion about security risks of Taler's trust model. +For details, refer to chapter 4.1.3 of \cite{dold:the-gnu-taler-system}. + +\begin{figure}[htp] + \includegraphics[height=0.5\textwidth]{taler-pki.png} + \centering + \caption{GNU Taler PKI entities (source: \cite{dold:the-gnu-taler-system})} + \label{fig:taler-pki} +\end{figure} + +\subsubsection{Exchange} +The exchange has to expose an API in order to enable customers (wallets), merchants and auditors to access keys and other information. +An exchange has a long term master key (Ed25519 key) and a base URL. +The URL and the long term \ac{MK} identifies an exchange. +The \ac{MK} is only used as an offline signing key and should be stored on an air-gapped machine. +Further, the exchange has online signing keys (Ed25519 key), which are signed by the exchanges \ac{MK}. +This \ac{MK} is on his side signed by one or possibly more auditors master key(s). +The exchange's (online) signing keys are used to sign API responses. +The denomination keys of an exchange are also signed by the exchanges offline \ac{MK} and the auditors \ac{MK}. +The bank accounts supported by the exchange for withdrawals and deposits are also signed by the exchanges offline \ac{MK}. + +API requests are made to the base URL appending the name of the endpoint (eg. /keys) +The endpoint /keys is used to get the exchanges signing keys and other information. +Similar to the \ac{CA} trust model, the client (customer or merchant) can validate the signature of the keys, with the list of trusted auditor certs. + +\subsubsection{Coins} +As seen in the withdrawal protocol blind signatures are done with RSA public keys (section \ref{sec:blind-rsa-sign}). +These keys are called denomination keys and they represent the coin value of the signed coins. +The following information concerning the denomination keys are signed by the exchanges master key (citation from \cite{dold:the-gnu-taler-system} chapter 4.1.3): +\begin{itemize} + \item The RSA public key + \item The start date, after which coins of this denomination can be withdrawn and deposited. + \item The withdraw expiration date, after which coins cannot be withdrawn anymore, must be after the start date. + \item The deposit expiration date, after which coins cannot be deposited anymore, must be after the withdraw expiration date. + \item The legal expiration date, after which the exchange can delete all records about operations with coins of this denominations, must be (typically quite a long time!) after the deposit expiration date. + \item The fees for a withdraw, deposit, refresh and refund operation with this coin, respectively. +\end{itemize} + +As mentioned, the denomination keys are signed by the exchanges \ac{MK} and also by the auditor. + +\subsubsection{Merchant} +The merchant has one Ed25519 public key. +With that key the merchant authenticates to the exchange and signs responses to the customer. +Depending on the jurisdiction, an exchange needs to comply to \ac{KYC} regulations. +A merchant which accepts payments from all exchanges (audited by a trusted auditor) therefore needs to fulfill \ac{KYC} registration for all accepted exchange separately. +This is needed to be legally compliant. \\ +Like the customer, also the merchant is configured with a set of trusted auditors and exchanges. +A merchant only accepts payments with coins of denominations from a trusted exchange which is audited by a trusted auditor. + +For this reason Taler separates this service into an isolated service, similar to on-premise or external payment gateways, which are used by most e-commerce shops nowadays. + +\subsubsection{Customer} +A customer has private keys of reserves that they own to authenticate with the exchange. +The public key was communicated to the exchange with the wire transfer. (A bank however is not part of Taler's \ac{PKI}.) +A customer is therefore not registered with an exchange. + +Further a customer possesses the private keys of his coins and stores them in a digital wallet. +\subsubsection{Security Discussion} +Taler's trust model is technically similar to the \ac{CA} trust model we know from TLS certificates. +The trust anchor lies with the auditors, whose certificates are pre-configured by the merchant or customer respectively. +However, trust is always somehow attackable. +That does not mean that there is a security issue in the trust model. +When the list of trusted auditor certs of a customer/merchant somehow can be manipulated, the trust model breaks for this entity. \\ +One attack scenario would be to attack customers/merchants with a supply-chain attack on the wallets or merchant backends' implementation. +With software supply-chain attacks on the rise in 2020/21 (although the concept is not new) such an attack could have a big impact. \\ +Since auditor certs are coupled with the wallet (or merchant) implementation, a bank, country, central bank or auditor will most likely publish a wallet and a merchant implementation for the corresponding Taler ecosystem. +%This would make it possible for the publisher to make changes on the Taler protocol for this specific implementation. \ No newline at end of file diff --git a/doc/cs/content/4_1_design.tex b/doc/cs/content/4_1_design.tex new file mode 100644 index 000000000..272f8da76 --- /dev/null +++ b/doc/cs/content/4_1_design.tex @@ -0,0 +1,458 @@ +\chapter{Protocol Design} +\label{chap:design} +This chapter describes the necessary changes on the protocol level to implement a Blind Schnorr Signature Scheme to Taler. + + +\section{Analysis of Current Protocols} +The blind RSA signature scheme is only used for coin signatures. +Note that we omitted protocols (or parts of them) where the coin signature is transmitted, but no other actions using it is performed. +\\\\ +\label{abort-idempotency} +An important property to mention here is \textit{\gls{abort-idempotency}}. +\Gls{idempotence} in the context of computer science is a property to ensure that the state of a system will not change, no matter how many times the same request was made. +A more in-depth explanation is given within the cited source \cite{yuchen:idempotence}.\\ +\textit{\gls{abort-idempotency}} goes a bit further. +When the protocol is aborted at any stage, for example due to power cuts or network issues, the protocol still needs to ensure that the same response is sent for the same request. +This is especially challenging when dealing with random values as we will see in the redesigned protocols in the following sections. +For \gls{RSABS} it is inherently easier to provide \textit{\gls{abort-idempotency}} since signature creation only needs one round-trip and requires less random values. + +The following protocols currently use \gls{RSABS}: +\begin{itemize} + \item \textbf{Withdraw Protocol:} + The customer uses the blind signature scheme to blind the coins before transmitting them to the exchange, which blindly signs it (standard RSA signature) and the returns the signatures. + After the customer receives the signatures, he unblinds and stores them together with the coins. + \\ Components: + \begin{itemize} + \item Customer + \item Exchange + \end{itemize} + \item \textbf{Deposit Protocol:} + During the Deposit, the exchange verifies the coin signature derived using the blind RSA signature scheme. + \\ Components: + \begin{itemize} + \item Exchange + \end{itemize} + \item \textbf{Refresh Protocol:} + The refresh protocol is used to derive a new coin from an old one which was partially spent. + Parts of the protocol are similar to the withdraw protocol, but it is more complex due to the added DH lock and cut-and-choose. + \\ Components: + \begin{itemize} + \item Customer + \item Exchange + \end{itemize} + \item \textbf{Tipping:} + Tipping is a variation of the withdraw protocol where the message containing the blinded planchets is transmitted to the merchant, who signs them using his reserve private, key and returns the signatures back to the customer. + Here, the details from the withdraw protocol apply. + \\ Components: + \begin{itemize} + \item Customer + \item Exchange + \end{itemize} + \item \textbf{Payback Protocol:} + The payback protocol distinguishes three different cases, which either use the refresh protocol or disclose either the withdraw transcript or refresh protocol transcript to the exchange. + \\ Components: + \begin{itemize} + \item Customer + \item Exchange + \end{itemize} +\end{itemize} + + +\section{Protocol Changes} +The goal of the thesis is to add support for the Clause Blind Schnorr Signature scheme to Taler, besides the existing \gls{RSABS} implementation (see section \ref{sec:blind-rsa-sign}). +For the design of the \gls{CSBS} the existing protocols with \gls{RSABS} were redesigned. + +The goal of the blind signature is to keep the exchange from knowing which coin a user withdraws and thus preventing the exchange linking a coin to a user. +The biggest impact is on the withdrawal and refresh protocols, but all protocols that include some operation around denomination signatures are affected. + +During the thesis the protocols will be redesigned, implemented and the differences to the current version will be outlined. +These results will be delivered to the Taler team. +Feedback is very important when (re)designing protocols. +For that reason the redesigned protocols were discussed and reviewed with Christian Grothoff multiple times. + +As signature scheme the Clause Blind Schnorr Signature Scheme described in section \ref{sec:clause-blind-schnorr-sig} was chosen for multiple reasons. +First of all it is currently considered to be secure (see \cite{cryptoeprint:2019:877}). +Schnorr Signatures on \gls{25519} are much shorter than RSA signatures. +This should provide notable performance improvements in speed and storage, and therefore scales better. +The paper describes a security analysis of the Blind Schnorr Signature scheme and introduces a modification (the "clause" part in the name) that is resistant to Wagner's algorithm (which solves ROS problem). + +\Gls{25519} \cite{bern:curve25519} will be used for the implementation because it is a widely accepted curve (see \cite{bernlange:safecurves}, \cite{rfc7748}) and is already used by Taler (Taler uses Ed25519 which is built upon \gls{25519}). + + +\subsection{Withdraw Protocol} +\label{sec:withdraw-protocol-schnorr} +The modified protocol using the Clause Blind Schnorr Signature Scheme is described in figures \ref{fig:withdrawal-process-schnorr-1} and \ref{fig:withdrawal-process-schnorr-2}. + +The proposed change introduces an additional round trip. +It must be prevented that the exchange has to track sessions or persist values during the first stage \ref{fig:withdrawal-process-schnorr-1}, while still ensuring \gls{abort-idempotency}. +In order to ensure \textit{\gls{abort-idempotency}}, the exchange has to generate the same $R_0,R_1$ for the same withdrawal request, while $r_0,r_1$ still needs to be unpredictable for the customer. +For this reason a withdrawal-nonce combined with a \gls{hkdf} comes into play. +The redesigned protocol makes extensive use of \gls{hkdf}'s functionality as \ac{PRNG} and one-way function, thus random becomes \textit{unpredictable}. + +In the beginning of the protocol, the customer generates a coin key pair. +Its private key is used to generate the withdraw-nonce $n_w$ and the blinding factors $\alpha_0, \alpha_1, \beta_0, \beta_1$. +The exchange uses the withdraw nonce together with the reserve key and a long-term secret to generate $r_0, r_1$. +The coin and denomination private keys can be used as long-term secrets due to the one-way property of the \gls{hkdf}. + +Another question evolved around which key to use for the derivation of $ r_0, r_1 $. +Obvious options are the denomination key or the exchange's online signing key. +The denomination key was chosen because it has the payback protocol in place that would handle coin recovery in case of a key compromise and subsequent revocation. + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p & & \text{reserve public key } W_p + \\ \text{denomination public key } D_p & & \text{denomination keys } d_s, D_p + \\ & & + \\\text{generate withdraw secret:} + \\ \omega := randombytes(32) + \\ \text{persist } \langle \omega, D_p \rangle + \\ n_w := \text{HKDF}(256, \omega,\text{"n"}) + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{n_w, D_p} & + % generate R + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & r_0 := \text{HKDF}(256,n_w || d_s, \text{"r0"}) + \\ & & r_1 := \text{HKDF}(256,n_w || d_s, \text{"r1"}) + \\ & & R_0 := r_0G + \\ & & R_1 := r_1G + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{R_0, R_1} & + \\ \text{derive coin key pair}: + \\ c_s := \text{HKDF}(256, \omega || R_0 || R_1,\text{"cs"}) + \\ C_p := \text{Ed25519.GetPub}(c_s) + % blinding + \\ \text{blind:} & & + \\ b_s := \text{HKDF}(256, \omega || R_0 || R_1,\text{"b-seed"}) + \\ \alpha_0 := \text{HKDF}(256, b_s, \text{"a0"}) + \\ \alpha_1 := \text{HKDF}(256, b_s, \text{"a1"}) + \\ \beta_0 := \text{HKDF}(256, b_s, \text{"b0"}) + \\ \beta_1 := \text{HKDF}(256, b_s, \text{"b1"}) + \\ R'_0 := R_0 + \alpha_0 G + \beta_0 D_p & & + \\ R'_1 := R_1 + \alpha_1 G + \beta_1 D_p & & + \\ c'_0 := H(R'_0, C_p) & & + \\ c'_1 := H(R'_1, C_p) & & + \\ c_0 := c'_0 + \beta_0 \mod p & & + \\ c_1 := c'_1 + \beta_1 \mod p & & + \\ + \\ & \textit{Continued in figure \ref{fig:withdrawal-process-schnorr-2}} & + \end{array}$ + } + \end{equation*} + \caption{Withdrawal process using Clause Blind Schnorr Signatures part 1} + \label{fig:withdrawal-process-schnorr-1} +\end{figure} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p & & \text{reserve public key } W_p + \\ \text{denomination public key } D_p & & \text{denomination keys } d_s, D_p + \\ + \\ & \textit{Continuation of figure \ref{fig:withdrawal-process-schnorr-1}} & + \\ + % sign with reserve sk + \\ \text{sign with reserve private key:} & & + \\ \rho_W := \langle n_w, D_p, c_0, c_1 \rangle & & + \\ \sigma_W := \text{Ed25519.Sign}(w_s, \rho_W) & & + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{W_p, \sigma_W, \rho_W} & + \\ & & \langle n_w, D_p, c_0, c_1 \rangle := \rho_W + % checks done by the exchange + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & \text{check } \text{Ed25519.Verify}(W_p, \rho_W, \sigma_W) + \\ & & b := \text{HKDF}(1,n_w || d_s, \text{"b"}) + \\ & & s \leftarrow \text{GetWithdraw}(n_w, D_p) + \\ & & \textbf{if } s = \bot + \\ & & r_b := \text{HKDF}(256,n_w || d_s, \text{"r}b\text{"}) + % sign coin + \\ & & s := r_b + c_b d_s \mod p + % the following db operations are atomic + \\ & & \text{decrease balance if sufficient and} + \\ & & \text{persist } \langle n_w, D_p, s \rangle + \\ & & \textbf{endif} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{b,s} & + % verify signature + \\ \text{verify signature:}& & + \\ \textbf{check if } sG = R_b + c_b D_p & & + % unblind signature + \\ \text{unblind:}& & + \\ s' := s + \alpha_b \mod p & & + \\ \text{verify signature:}& & + \\ \textbf{check if } s'G = R'_b + c'_b D_p & & + \\ \sigma_C := \langle R'_b, s' \rangle & & + \\ \text{resulting coin: } c_s, C_p, \sigma_C, D_p & & + + \end{array}$ + } + \end{equation*} + \caption{Withdrawal process using Clause Blind Schnorr Signatures part 2} + \label{fig:withdrawal-process-schnorr-2} +\end{figure} + + +\subsection{Deposit Protocol} +The deposit protocol remains unchanged, except for the verification of the coin signature. +To verify the signature, the exchange has to check if the following equation holds: +\begin{align*} + s'G & = R' + c' D_p + \\ &= R' + H(R', C_p) D_p +\end{align*} +$ s', R' $ together form the signature, $ D_p $ is the denomination public key and $ C_p $ is the coin public key. + +Further details regarding the verification process can be found in section \ref{sec:blind-schnorr-sig}. + + +\subsection{Refresh Protocol} +The refresh protocol blindly signs the new derived coins. +The replacement of \gls{RSABS} with the Clause Blind Schnorr Signature Scheme (see \ref{sec:clause-blind-schnorr-sig}) makes the refresh protocol a bit more complex. + +\subsubsection{RefreshDerive Schnorr} +The RefreshDerive protocol is described in figure \ref{fig:refresh-derive-schnorr}. +For this protocol, the main change is that more values need to be derived somehow. +These blinding factors are also derived from $x$. +Then the challenges $\overline{c_0}$ and $\overline{c_1}$ are generated as in the Clause Blind Schnorr Signature Scheme. + +\begin{figure}[htp] + \centering + \fbox{% + \procedure[codesize=\small]{$\text{RefreshDerive}(t, D_{p(t)}, C_p, R_0, R_1)$}{% + T := \text{Curve25519.GetPub}(t) \\ + x := \textrm{ECDH-EC}(t, C_p) \\ + c'_s := \text{HKDF}(256, x, \text{"c"}) \\ + C_p' := \text{Ed25519.GetPub}(c'_s) \\ + b_s := \text{HKDF}(256, x || R_0 || R_1,\text{"b-seed"}) \\ + \alpha_0 := \text{HKDF}(256, b_s, \text{"a0"}) \\ + \alpha_1 := \text{HKDF}(256, b_s, \text{"a1"}) \\ + \beta_0 := \text{HKDF}(256, b_s, \text{"b0"}) \\ + \beta_1 := \text{HKDF}(256, b_s, \text{"b1"}) \\ + R'_0 = R_0 + \alpha_0 G + \beta_0 D_p \\ + R'_1 = R_1 + \alpha_1 G + \beta_1 D_p \\ + c'_0 = H(R'_0, C_p') \\ + c'_1 = H(R'_1, C_p') \\ + \overline{c_0} = c'_0 + \beta_0 \mod p \\ + \overline{c_1} = c'_1 + \beta_1 \mod p \\ + \pcreturn \langle T, c'_s, C_p', \overline{c_0}, \overline{c_1} \rangle + } + } + \caption[RefreshDerive algorithm]{The RefreshDerive replaced with Schnorr blind signature details. As before the uses the seed $s$ on the dirty coin for generating the new coin. + The new coin needs to be signed later on with the denomination key.} + \label{fig:refresh-derive-schnorr} +\end{figure} + +\subsubsection{Refresh Protocol} +\label{sec:refresh-protocol} +In the commit phase (see figure \ref{fig:refresh-commit-part1}) there needs to be requested an $R_0$ and $R_1$ before deriving the new coins. +There now needs to be calculated two different commit hashes, one for $\overline{c_0}$ and one for $\overline{c_1}$. +The exchange needs to additionally generate a random $b \leftarrow \{0,1\}$ to choose a $\overline{c_b}$. +The reveal phase (see figure \ref{fig:refresh-commit-part2}) now is continued only with the chosen $\overline{c_b}$. +In the reveal phase, the RSA signing and unblinding is exchanged with Schnorr's blind signature counterparts. + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{denomination public key } D_p & & \text{old denomination keys } d_{s(0)} D_{p(0)} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_c^{(0)} \rangle && \text{new denomination keys } d_s, D_P + % request r + \\ & & + \\ \omega := randombytes(32) + \\ \text{persist } \langle \omega, D_p \rangle + %\\ s_w := \text{HKDF}(256, c_s^{(0)},\text{"n"}) + \\ n_r := \text{HKDF}(256, \omega,\text{"n"}) + % sign with reserve sk + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{n_r, D_p} & + % generate R + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & r_0 := \text{HKDF}(256,n_r || d_s, \text{"r0"}) + \\ & & r_1 := \text{HKDF}(256,n_r || d_s, \text{"r1"}) + \\ & & R_0 := r_0G + \\ & & R_1 := r_1G + \\ & \xleftarrow[\rule{2cm}{0pt}]{R_0, R_1} & + % refresh request + \\ \textbf{for } i = 1, \dots, \kappa: % generate k derives + %\\ s_i \leftarrow \{0,1\}^{256} % seed generation + \\ t_i := \text{HKDF}(256, \omega || R_0 || R_1,\text{"t} i \text{"} ) % seed generation + \\ X_i := \text{RefreshDerive}(t_i, D_p, C_p^{(0)}, R_0, R_1) + \\ (T_i, c_s^{(i)}, C_p^{(i)}, \overline{c_0}, \overline{c_1}):= X_i + \\ \textbf{endfor} + \\ h_T := H(T_1, \dots, T_k) + \\ h_{\overline{c_0}} := H(\overline{c_{0_1}},\dots, \overline{c}_{0_k}) + \\ h_{\overline{c_1}} := H(\overline{c_{1_1}},\dots, \overline{c}_{1_k}) + \\ h_{\overline{c}} := H(h_{\overline{c_0}}, h_{\overline{c_1}}) + \\ h_C := H(h_T, h_{\overline{c}}) + \\ \rho_{RC} := \langle h_C, D_p, \text{ } D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} \rangle + \\ \sigma_{RC} := \text{Ed25519.Sign}(c_s^{(0)}, \rho_{RC}) + \\ \text{Persist refresh-request} + \\ \langle \omega, R_0, R_1, \rho_{RC}, \sigma_{RC} \rangle + \\ + \\ & \textit{Continued in figure \ref{fig:refresh-commit-part2}} & + \end{array}$ + } + \end{equation*} + \caption{Refresh protocol (commit phase part 1) using Clause Blind Schnorr Signatures} + \label{fig:refresh-commit-part1} +\end{figure} + + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + \text{Customer} & & \text{Exchange} + \\ & \textit{Continuation of} + \\ & \textit{figure \ref{fig:refresh-commit-part1}} + \\ + \\ & \xrightarrow[\rule{2cm}{0pt}]{\rho_{RC}, \sigma_{RC}} & + % Exchange checks refresh request + \\ & & \langle h_C, D_p, D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} \rangle := \rho_{RC} + \\ & & \textbf{check} \text{ Ed25519.Verify}(C_p^{(0)}, \sigma_{RC}, \rho_{RC}) + \\ + \\ & & \gamma \leftarrow \text{GetOldRefresh}(\rho_{RC}) + \\ & & \textbf{Comment: }\text{GetOldRefresh}(\rho_{RC} \mapsto + \\ & & \{\bot, \gamma \}) + \\ & & \pcif \gamma = \bot + \\ & & v := \text{Denomination}(D_p) + \\ & & \textbf{check } \text{IsOverspending}(C_p^{(0)}, D_ {p(0)}, v) + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & \textbf{check } \text{Schnorr.Verify}(D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)}) + \\ & & \text{MarkFractionalSpend}(C_p^{(0)}, v) + \\ & & \gamma \leftarrow \{1, \dots, \kappa\} + \\ & & \text{Persist refresh-record } \langle \rho_{RC},\gamma \rangle + \\ & \xleftarrow[\rule{2cm}{0pt}]{\gamma} & + % Check challenge and send challenge response (reveal not selected msgs) + \\ \textbf{check } \text{IsConsistentChallenge}(\rho_{RC}, \gamma) + \\ \textbf{Comment: } \text{IsConsistentChallenge}\\(\rho_{RC}, \gamma) \mapsto \{ \bot,\top \} + \\ + \\ \text{Persist refresh-challenge} \langle \rho_{RC}, \gamma \rangle + \\ S := \langle t_1, \dots, t_{\gamma-1}, t_{\gamma+1}, \dots,t_\kappa \rangle % all seeds without the gamma seed + \\ \rho_L := \langle C_p^{(0)}, D_p, T_{\gamma}, \overline{c_0}_\gamma, \overline{c_1}_\gamma, n_r \rangle + \\ \rho_{RR} := \langle \rho_L, S \rangle + \\ \sigma_{L} := \text{Ed25519.Sign}(c_s^{(0)}, \rho_{L}) + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RR},\rho_L, \sigma_{L}} & + \\ + \\ & \textit{Continued in} & + \\ & \textit{figure \ref{fig:refresh-reveal-part1}} & + \end{array}$ + } + \end{equation*} + \caption{Refresh protocol (commit phase part 2) using Clause Blind Schnorr Signatures} + \label{fig:refresh-commit-part2} +\end{figure} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ & \textit{Continuation of} + \\ & \textit{figure \ref{fig:refresh-commit-part2}} + \\ + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RR},\rho_L, \sigma_{L}} & + % check revealed msgs and sign coin + \\ & & \langle C_p^{(0)}, D_p, T_{\gamma}, \overline{c_0}_\gamma, \overline{c_1}_\gamma, n_r \rangle := \rho_L + \\ & & \langle T'_\gamma, \overline{c_0}_\gamma, \overline{c_1}_\gamma, S \rangle := \rho_{RR} + \\ & & \langle t_1,\dots,t_{\gamma-1},t_{\gamma+1},\dots,t_\kappa \rangle := S + \\ & & \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \sigma_L, \rho_L) + \\ & & b := \text{HKDF}(1,n_r || d_{s(i)}, \text{"b"}) + \\ & & \textbf{for } i = 1,\dots, \gamma-1, \gamma+1,\dots, \kappa + \\ & & X_i := \text{RefreshDerive}(t_i, D_p, C_p^{(0)} \\ &&, R_0, R_1) + \\ & & \langle T_i, c_s^{(i)}, C_p^{(i)}, \overline{c_1}_i, \overline{c_2}_i \rangle := X_i + \\ & & \textbf{endfor} + \\ & & h_T' = H(T_1,\dots,T_{\gamma-1},T'_{\gamma},T_{\gamma+1},\dots,T_\kappa) + \\ & & h_{\overline{c_0}}' := H(\overline{c_{0_1}},\dots, \overline{c}_{0_k}) + \\ & & h_{\overline{c_1}}' := H(\overline{c_{1_1}},\dots, \overline{c}_{1_k}) + \\ & & h_{\overline{c}}' := H(h_{\overline{c_0}}, h_{\overline{c_1}}) + \\ & & h_C' = H(h_T', h_{\overline{c}}') + \\ & & \textbf{check } h_C = h_C' + \\ & & r_b := \text{HKDF}(256,n_r || d_s, \text{"r}b\text{"}) + \\ & & \overline{s}_{C_p}^{(\gamma)} = r_b + \overline{c_{b_\gamma}} d_s \mod p + \\ & & \text{persist } \langle \rho_L, \sigma_L \rangle + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{b, \overline{s}_C^{(\gamma)}} & + % Check coin signature and persist coin + % unblind signature + \\ \text{unblind:}& & + \\ s_C'^{(\gamma)} := \overline{s}_C^{(\gamma)} + \alpha_b \mod p & & + \\ \text{verify signature:}& & + \\ \textbf{check if } \overline{s'}_C^{(\gamma)}G \equiv R'_b + \overline{c'_0}_\gamma D_p & & + \\ \sigma_C^{(\gamma)} := \langle s_{C}'^{(\gamma)},R_b' \rangle + \\ \text{Persist coin} \langle D_p, c_s^{(\gamma)}, C_p^{(\gamma)}, \sigma_C^{(\gamma)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Refresh protocol (reveal phase) using Clause Blind Schnorr Signatures} + \label{fig:refresh-reveal-part1} +\end{figure} +\newpage +\subsubsection{Linking Protocol} +\label{sec:refresh-link} +The beginning of the linking protocol (see figure \ref{fig:refresh-link}) is the same as in the current protocol. +After the customer received the answer $L$ the only difference is in obtaining the coin. +To re-obtain the derived coin, the same calculations as in \ref{fig:refresh-derive-schnorr} are made. +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_{C}^{(0)} \rangle + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{C_{p(0)}} & + \\ & & L := \text{LookupLink}(C_{p(0)}) + \\ & & \textbf{Comment: } \text{LookupLink}(C_p^{(0)}) \mapsto + \\ & & \{\langle \rho_L^{(i)}, \sigma_L^{(i)}, \overline{\sigma}_C^{(i)}, b \rangle\} + %\\ & & \{\langle C_{p(0)}, D_{p(t)},\overline{\sigma}_C^{(i)}, b^{(i)}, R_b^{(i)}\rangle\} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{L} & + \\ \textbf{for } \langle \rho_L^{(i)}, \overline{\sigma}_L^{(i)}, \overline{\sigma}_C^{(i)}, b \rangle\ \in L + + %\\ & & \langle C_p^{(0)}, D_{p(t)}, T_{\gamma}, \overline{c_0}_\gamma, \overline{c_1}_\gamma, n_r \rangle := \rho_L + \\ \langle \hat{C}_p^{(i)}, D_p^{(i)}, T_\gamma^{(i)}, \overline{c_0}_\gamma^{(i)}, \overline{c_1}_\gamma^{(i)}, n_r \rangle := \rho_L^{(i)} + \\ \langle \overline{s}_C^{(i)}, R_b^{(i)} \rangle := \overline{\sigma}_C^{(i)} + \\ \textbf{check } \hat{C}_p^{(i)} \equiv C_p^{(0)} + \\ \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \rho_{L}^{(i)}, \sigma_L^{(i)}) + \\ \langle \overline{s}_C^{(i)}, R_b^{(i)} \rangle := \sigma_C^{(i)} + \\ x_i := \text{ECDH}(c_s^{(0)}, T_{\gamma}^{(i)}) + \\ c_s^{(i)} := \text{HKDF}(256, x, \text{"c"}) + \\ C_p^{(i)} := \text{Ed25519.GetPub}(c_s^{(i)}) + \\ b_s^{(i)} := \text{HKDF}(256, x_i || R_0^{(i)} || R_1^{(i)},\text{"b-seed"}) + \\ \alpha_b := \text{HKDF}(256, b_s^{(i)}, \text{"a}b\text{"}) + \\ \beta_b := \text{HKDF}(256, b_s^{(i)}, \text{"b}b\text{"}) + \\ {R'}_b^{(i)} = R_b^{(i)} + \alpha_b G + \beta_b D_p^{(i)} + \\ c'_b = H(R'_b, C_p^{(i)}) + \\ c_b = c'_b + \beta_b \mod p + \\ s_C'^{(i)} := \overline{s}_C^{(i)} + \alpha_b \mod p + \\ \sigma_C^{(i)} := \langle s_C'^{(i)}, R_b' \rangle + \\ \textbf{check } s'{_C^{(i)}}G \equiv {R'}_b^{(i)} + c'_b D_p^{(i)} + \\ \text{(Re-)obtain coin} \langle D_p^{(i)},c_s^{(i)}, C_p^{(i)}, \sigma_C^{(i)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Linking protocol using Clause Blind Schnorr Signatures} + \label{fig:refresh-link} +\end{figure} + + +\subsection{Tipping} +Tipping remains unchanged, except for the content of the message $ \rho_W = D_p, c_0, c_1 $ signed by the merchant using its reserve private key. + +\subsection{Payback Protocol} +The payback protocol distinguishes three different cases, which all depend on the state of a coin whose denomination key has been revoked. +The following listing outlines the necessary changes on the protocol, please refer to Dold's documentation section 2.2.1 \cite{dold:the-gnu-taler-system} for details regarding the different cases. +\begin{itemize} + \item \textbf{The revoked coin has never been seen by the exchange}: + \\The withdraw transcript (and verification) must be adjusted in order for the exchange to be able to retrace the blinding. + \item \textbf{The coin has been partially spent}: + \\In this case the refresh protocol will be invoked on the coin. + The necessary changes are outlined in \ref{sec:refresh-protocol}. + \item \textbf{The revoked coin has never been seen by the exchange and resulted from a refresh operation}: + \\The refresh protocol transcript and its blinding factors must be adjusted to consider the changes in the blind signature scheme. +\end{itemize} diff --git a/doc/cs/content/4_2_specification.tex b/doc/cs/content/4_2_specification.tex new file mode 100644 index 000000000..efe6a3c3d --- /dev/null +++ b/doc/cs/content/4_2_specification.tex @@ -0,0 +1,790 @@ +\chapter{Protocol Specification} +\label{chap:spec} +The proposed Taler protocols using the Clause Blind Schnorr Signature Scheme will be implemented as an additional option besides the existing \gls{RSABS} variant of the protocol as suggested by Christian Grothoff. +A Taler Exchange operator should be able to configure whether he wants to use \gls{RSABS} or \gls{CSBS}. +\\This variant allows to choose the signature scheme globally or per denomination. +Furthermore, it allows a change of signature scheme in a non-breaking way by revoking (or letting expire) a denomination and offering new denominations with the other scheme. +\\ +The following key points are specified in this chapter: +\begin{itemize} + \item Architecture of the different components + \item Explain and specify needed changes + \item Data strucutures + \item Public \acp{API} + \item Persistence + \item Used libraries +\end{itemize} + +\section{Architecture} +Before specifying the implementation of the different protocols, a deeper understanding of the technical architecture of Talers components is needed. +this section introduces the architecture of the exchange and wallet components and explains where the needed changes need to be implemented on a high-level. + +\subsection{Exchange} +An introduction to the exchange can be found in section \ref{sec:exchange}. +An exchange operator needs to run and maintain some additional services besides Taler's exchange. +Although this is not directly relevant for the implementation, it helps to better understand the environment in which the exchange runs. +The perspective of an exchange operator can be seen in figure \ref{fig:taler:exchange-operator-architecture}. + +\begin{figure}[h!] + \begin{adjustbox}{max totalsize={.9\textwidth}{.7\textheight},center} + \begin{tikzpicture} + \tikzstyle{def} = [node distance= 5em and 6.5em, inner sep=1em, outer sep=.3em]; + \node (origin) at (0,0) {}; + \node (exchange) [def,above=of origin,draw]{Exchange}; + \node (nexus) [def, draw, below right=of exchange] {Nexus}; + \node (corebanking) [def, draw, below left=of nexus] {Core Banking}; + \node (nginx) [def, draw, above=of exchange]{Nginx}; + \node (postgres) [def, draw, below left=of exchange]{Postgres}; + \node (postgres-nexus) [def, draw, below right=of nexus]{Postgres}; + + \tikzstyle{C} = [color=black, line width=1pt] + + \draw [<-, C] (exchange) -- (nginx) node [midway, above, sloped] (TextNode) {REST API}; + \draw [<-, C] (postgres) -- (exchange) node [midway, above, sloped] (TextNode) {SQL}; + \draw [<-, C] (postgres-nexus) -- (nexus) node [midway, above, sloped] (TextNode) {SQL}; + \draw [<-, C] (nexus) -- (exchange) node [midway, above, sloped] (TextNode) {Internal REST API}; + \draw [<-, C] (corebanking) -- (nexus) node [midway, above, sloped] (TextNode) {EBICS/FinTS}; + + \end{tikzpicture} + \end{adjustbox} + \caption{Taler exchange operator architecture (source: \cite{taler-presentation})} + \label{fig:taler:exchange-operator-architecture} +\end{figure} + +The software architecture of the exchange can be seen in figure \ref{fig:taler:exchange-architecture}. +The API runs under the httpd service, where the API endpoints need to be adjusted/added to incorporate the changes of this thesis. +The httpd server has no access to the private keys of the denomination and online signing keys. +Only the corresponding security module can perform operations requiring the private key. +Further the keys are also managed by these security modules. +To support \gls{CSBS} a new security module, which performs signature operations, is added. +To persist the new data structures, the postgres helpers need to be adjusted to serialize/deserialize the new \gls{CSBS} data structures. +More details on what changes are needed in these places is discussed in the following sections. + +\begin{figure}[h!] + \begin{center} + \begin{tikzpicture} + \tikzstyle{def} = [node distance=2em and 2.5em, inner sep=1em, outer sep=.3em]; + \node (origin) at (0,0) {}; + \node [blue] (httpd) [def,above=of origin,draw]{httpd}; + \node (secmod-rsa) [def, draw, right=of httpd] {secmod-rsa}; + \node (secmod-eddsa) [def, draw, left=of httpd] {secmod-eddsa}; + \node [blue](postgres) [def, draw, below=of httpd]{Postgres}; + \node [mGreen] (secmod-cs) [def, draw, left=of postgres]{secmod-cs}; + \node (aggregator) [def, draw, right=of postgres]{aggregator}; + \node (transfer) [def, draw, below left=of postgres]{transfer}; + \node (wirewatch) [def, draw, below right=of postgres]{wirewatch}; + \node (nexus) [def, draw, below=of postgres]{Nexus}; + + \tikzstyle{C} = [color=black, line width=1pt] + + \draw [<->, C] (httpd) -- (postgres) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (httpd) -- (secmod-rsa) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (httpd) -- (secmod-eddsa) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (httpd) -- (secmod-cs) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (aggregator) -- (postgres) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (wirewatch) -- (postgres) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (transfer) -- (postgres) node [midway, above, sloped] (TextNode) {}; + \draw [->, C] (transfer) -- (nexus) node [midway, above, sloped] (TextNode) {}; + \draw [<-, C] (wirewatch) -- (nexus) node [midway, above, sloped] (TextNode) {}; + \end{tikzpicture} + \end{center} + \caption{Taler exchange architecture (source: \cite{taler-presentation})} + \label{fig:taler:exchange-architecture} +\end{figure} + +\subsection{Wallet} +The architecture of the wallet implementation (as seen in figure \ref{fig:taler:wallet-architecture}) is quite straightforward. +To add support for \gls{CSBS} in the wallet, the cryptographic routines need to be reimplemented in Typescript. +Taler uses tweetnacl \cite{bern:tweetnacl} which provides functionality for the group operations. +There are existing \gls{hkdf} and \gls{fdh} implementations, that can be reused.\\ +Furthermore, the Taler protocols need to be adjusted to support \gls{CSBS} in the wallet-core. + +\begin{figure}[h!] + \begin{center} + \begin{tikzpicture} + \tikzstyle{def} = [node distance= 5em and 4.5em, inner sep=1em, outer sep=.3em]; + \node (origin) at (0,0) {}; + \node (gui) [def,above=of origin,draw]{wallet-gui}; + \node [blue](core) [def,below=of gui,draw]{wallet-core}; + \node (sync) [def, draw, below left=of core] {Sync}; + \node (taler) [def, draw, below right=of core] {Taler}; + \node (anastasis) [def, draw, below=of core] {Anastasis}; + + \tikzstyle{C} = [color=black, line width=1pt] + \draw [<->, C] (gui) -- (core) node [midway, above, sloped] (TextNode) {}; + \draw [<->, C] (core) -- (sync) node [midway, above, sloped] (TextNode) {Backup}; + \draw [<->, C] (core) -- (taler) node [midway, above, sloped] (TextNode) {Payment}; + \draw [<->, C] (core) -- (anastasis) node [midway, above, sloped] (TextNode) {Key Escrow}; + \end{tikzpicture} + \end{center} + \caption{Taler wallet architecture (source: \cite{taler-presentation})} + \label{fig:taler:wallet-architecture} +\end{figure} + +\section{Persistence} +The Clause Blind Schnorr Signature scheme is quite different to \gls{RSABS}. +Despite the differences, the database model does not need to be changed. +The only change needed an additional type field, specifying whether RSA or CS is used as signature algorithm. +To persist the new structs introduced with the support for \gls{CSBS}, only the postgres helpers need to support serialization and deserialization of the new structs. + +\section{Testing} +We will partially use test-driven development, meaning that we will write tests (at least for the known good case) before implementing functions, and extend them during and after development. +This allows us to check the functionality (code section, function(s)) during development, while being able to extend testing whenever we identify new test cases during development. + +Test cases can be used to verify different aspects of a functionality. +These are the ones we will focus on. +\begin{itemize} + \item \textbf{Known good}: + Known good cases test whether a functionality works as expected. + They are the most useful during development, because they indicate whether the code is working as expected. + \item \textbf{Known Bad}: + Known bad cases test whether functionality that is known not to work behaves as expected. + \item \textbf{Determinism}: + This case type checks whether the same input leads to the same output. + It is important for code that must work deterministic (same output), non-deterministic (e.g. random output) or based on a state that impacts the functionality. + \item \textbf{Performance testing}: + Performance testing is used to gather timing information that can be used to identify functionality with long duration, or to compare performance between different implementations or major changes. + We will restrict performance testing to the comparison of the Blind RSA Signature Scheme and the Clause Blind Schnorr Signature Scheme. +\end{itemize} + + +\section{Signature Scheme Operations in GNUnet} +\label{sec:specification-signature-scheme} + +The signature scheme operations implemented are needed in all other parts of the implementation. +Taler's cryptographic primitives (e.g. \gls{RSABS}, \gls{hkdf}, hash functions) are mostly implemented in GNUnet utils, therefore the Clause Blind Schnorr Signature routines will be implemented in GNUnet too. +It is important to provide a clear API for the cryptographic routines and to test them thoroughly. +Libsodium will be used for finite field arithmetic (\cite{libsodium:finite-field-arithmetic}) and for other functionality when available (e.g. for key generation). +Thus, a widely used and well tested cryptographic library is used for group operations. + +For \acl{FDH} and \gls{hkdf} existing implementations provided by GNUnet are used. +The \gls{hkdf} is used with SHA-512 for the extraction phase and SHA-256 for the expansion phase. + +\subsection{Data Structures} +Libsodium represents Ed25519 points and scalars as 32-byte char arrays. +To provide a more user-friendly \ac{API}, structs were created to represent each type. +For example \texttt{struct GNUNET\_CRYPTO\_CsPrivateKey} or \texttt{struct GNUNET\_CRYPTO\_RSecret} +The main reason is to increase readability and to prevent misusage of the \ac{API}. +Unlike RSA, our \gls{CSBS} on Ed25519 data structures have a fixed sizes. +The different data structures can be found in table \ref{tab:datastruct-crypto}. + +\begin{table}[ht] + \centering + \resizebox{0.95\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Values} & \textbf{Data Structure} & \textbf{Data Type} \\\hline + Curve25519 Scalar & {\small GNUNET\_CRYPTO\_Cs25519Scalar} & 32 byte char array\\\hline + Curve25519 Point & {\small GNUNET\_CRYPTO\_Cs25519Point} & 32 byte char array\\\hline + Private Key & {\small GNUNET\_CRYPTO\_CsPrivateKey} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + Public Key & {\small GNUNET\_CRYPTO\_CsPublicKey} & {\small GNUNET\_CRYPTO\_Cs25519Point}\\\hline + $\alpha, \beta$ & {\small GNUNET\_CRYPTO\_CsBlindingSecret} & {\footnotesize 2x GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + $r$ & {\small GNUNET\_CRYPTO\_CsRSecret} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + $R$ & {\small GNUNET\_CRYPTO\_CsRPublic} & {\small GNUNET\_CRYPTO\_Cs25519Point}\\\hline + $c$ & {\small GNUNET\_CRYPTO\_CsC} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + $s$ & {\small GNUNET\_CRYPTO\_CsBlindS} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + $s'$ & {\small GNUNET\_CRYPTO\_CsS} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\\hline + $\sigma := \langle s',R' \rangle$ & {\small GNUNET\_CRYPTO\_CsSignature} & {\small GNUNET\_CRYPTO\_Cs25519Scalar}\\ + & & {\small GNUNET\_CRYPTO\_Cs25519Point}\\\hline + Nonce & {\small GNUNET\_CRYPTO\_CsNonce} & 32 byte char array\\\hline + \end{tabular} + \caption{Data structures for cryptographic routines} + \label{tab:datastruct-crypto} +\end{minipage}} +\end{table} + + + +\subsection{Library API} +The public \ac{API} and related data structures are specified in the C header file \url{src/include/gnunet_crypto_lib.h} in the GNUnet repository \cite{gnunet-git}. +It was developed in multiple iterations based on feedback from Christian Grothoff. +The complete C header \ac{API} can be found in the repository. +This section provides an overview of the implemented crypto API. + +Some design decisions need to be explained further: +\begin{itemize} + \item In order to prevent misusage of our implementation and increase readability, the functions that represent different stages in the signature scheme takes different data types as in- and output. + Internally most variables are either scalars or curve points (except for nonces, secrets and messages). + \item Operations that are performed twice in the Clause Blind Schnorr Signature Scheme (e.g. derivation of $ r $) do not have to be called twice. + Instead, the API returns an array of two instead of a single value.\\ + For these functions, we also optimized the \gls{hkdf} (as proposed by Christian Grothoff). + Instead of calling \gls{hkdf} twice (with different salts, e.g. "r0" and "r1"), we call it one time (e.g. with salt "r") and double the output length. + \item The cryptographic hash function used to derive $ c' $ (hash of $ R' $ and message) must map the results into the main subgroup for scalars, meaning that it has to be a \gls{fdh} (see \ref{sec:rsa-fdh}). +\end{itemize} + +The following API examples should provide an overview on how the API works and how to use it. + +First of all the API must provide functionality to create a \gls{25519} keypair as in listing \ref{lst:crypto-keypair-api} + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet create keypair API}, label={lst:crypto-keypair-api}] +/** + * Create a new random private key. + * + * @param[out] priv where to write the fresh private key + */ +void +GNUNET_CRYPTO_cs_private_key_generate ( + struct GNUNET_CRYPTO_CsPrivateKey *priv); + + +/** + * Extract the public key of the given private key. + * + * @param priv the private key + * @param[out] pub where to write the public key + */ +void +GNUNET_CRYPTO_cs_private_key_get_public ( + const struct GNUNET_CRYPTO_CsPrivateKey *priv, + struct GNUNET_CRYPTO_CsPublicKey *pub); +\end{lstlisting} + +The signer needs an API to generate his secret $r$ and calculate his public point $R$. +As specified in the redesign of the protocols, the r must not be chosen randomly because we need to provide \textit{\gls{abort-idempotency}}. However, the secret $r$ still needs to be \textit{unpredictable} and look random to the client. +The r\_derive API derives such a secret $r$ from a nonce and a long-term secret with \gls{hkdf}. +Further, the API ensures that a caller must generate two secret $r$ as in the Clause Blind Schnorr Signature scheme. This should discourage people from using the unsecure Blind Schnorr Signature scheme. See \ref{lst:crypto-rderive-api}. + + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet r derive API}, label={lst:crypto-rderive-api}] + /** + * Derive a new secret r pair r0 and r1. + * In original papers r is generated randomly + * To provide abort-idempotency, r needs to be derived but still needs to be UNPREDICTABLE + * To ensure unpredictability a new nonce should be used when a new r needs to be derived. + * Uses HKDF internally. + * Comment: Can be done in one HKDF shot and split output. + * + * @param nonce is a random nonce + * @param lts is a long-term-secret in form of a private key + * @param[out] r array containing derived secrets r0 and r1 + */ + void + GNUNET_CRYPTO_cs_r_derive (const struct GNUNET_CRYPTO_CsNonce *nonce, + const struct GNUNET_CRYPTO_CsPrivateKey *lts, + struct GNUNET_CRYPTO_CsRSecret r[2]); + + +/** + * Extract the public R of the given secret r. + * + * @param r_priv the private key + * @param[out] r_pub where to write the public key + */ + void + GNUNET_CRYPTO_cs_r_get_public (const struct GNUNET_CRYPTO_CsRSecret *r_priv, + struct GNUNET_CRYPTO_CsRPublic *r_pub); +\end{lstlisting} + + +Same as the r\_derive, the blinding secrets are also derived and not generated randomly. +The blinding secrets are generated by a client who provides a secret as seed to derive the secrets from as in listing \ref{lst:crypto-blinding-secrets-api}. + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet blinding secrets derive API}, label={lst:crypto-blinding-secrets-api}] +/** + * Derives new random blinding factors. + * In original papers blinding factors are generated randomly + * To provide abort-idempotency, blinding factors need to be derived but still need to be UNPREDICTABLE + * To ensure unpredictability a new nonce has to be used. + * Uses HKDF internally + * + * @param secret is secret to derive blinding factors + * @param secret_len secret length + * @param[out] bs array containing the two derivedGNUNET_CRYPTO_CsBlindingSecret + */ +void +GNUNET_CRYPTO_cs_blinding_secrets_derive ( + const struct GNUNET_CRYPTO_CsNonce *blind_seed, + struct GNUNET_CRYPTO_CsBlindingSecret bs[2]); +\end{lstlisting} + +Further the Clause Blind Schnorr API provides an API to calculate the two blinded c of the message with the two public $R$, the blinding factors and the public key as in listing \ref{lst:crypto-calc-c-api}. + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet calculate blinded c API}, label={lst:crypto-calc-c-api}] +/** + * Calculate two blinded c's + * Comment: One would be insecure due to Wagner's algorithm solving ROS + * + * @param bs array of the two blinding factor structs each containing alpha and beta + * @param r_pub array of the two signer's nonce R + * @param pub the public key of the signer + * @param msg the message to blind in preparation for signing + * @param msg_len length of message msg + * @param[out] blinded_c array of the two blinded c's + */ +void +GNUNET_CRYPTO_cs_calc_blinded_c ( + const struct GNUNET_CRYPTO_CsBlindingSecret bs[2], + const struct GNUNET_CRYPTO_CsRPublic r_pub[2], + const struct GNUNET_CRYPTO_CsPublicKey *pub, + const void *msg, + size_t msg_len, + struct GNUNET_CRYPTO_CsC blinded_c[2]); +\end{lstlisting} + +The sign function in our API is called sign\_derive, since we derive $b \in \{0,1\}$ from the long-term secret and then calculate the signature scalar of $c_b$. +See listing \ref{lst:crypto-sign-api}. + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet sign API}, label={lst:crypto-sign-api}] +/** + * Sign a blinded c + * This function derives b from a nonce and a longterm secret + * In original papers b is generated randomly + * To provide abort-idempotency, b needs to be derived but still need to be UNPREDICTABLE. + * To ensure unpredictability a new nonce has to be used for every signature + * HKDF is used internally for derivation + * r0 and r1 can be derived prior by using GNUNET_CRYPTO_cs_r_derive + * + * @param priv private key to use for the signing and as LTS in HKDF + * @param r array of the two secret nonce from the signer + * @param c array of the two blinded c to sign c_b + * @param nonce is a random nonce + * @param[out] blinded_signature_scalar where to write the signature + * @return 0 or 1 for b (see Clause Blind Signature Scheme) + */ +int +GNUNET_CRYPTO_cs_sign_derive( + const struct GNUNET_CRYPTO_CsPrivateKey *priv, + const struct GNUNET_CRYPTO_CsRSecret r[2], + const struct GNUNET_CRYPTO_CsC c[2], + const struct GNUNET_CRYPTO_CsNonce *nonce, + struct GNUNET_CRYPTO_CsBlindS *blinded_signature_scalar); +\end{lstlisting} + +The API for the unblind operation can be called with the blinding secrets and the signature scalar received from the signer as in listing \ref{lst:crypto-unblind-api}. + +\begin{lstlisting}[style=bfh-c,language=C, caption={GNUnet unblind API}, label={lst:crypto-unblind-api}] + /** + * Unblind a blind-signed signature using a c that was blinded + * + * @param blinded_signature_scalar the signature made on the blinded c + * @param bs the blinding factors used in the blinding + * @param[out] signature_scalar where to write the unblinded signature + */ +void +GNUNET_CRYPTO_cs_unblind ( + const struct GNUNET_CRYPTO_CsBlindS *blinded_signature_scalar, + const struct GNUNET_CRYPTO_CsBlindingSecret *bs, + struct GNUNET_CRYPTO_CsS *signature_scalar); +\end{lstlisting} + +The verify API takes the message and its signature with the public key and returns GNUNET\_OK for a valid signature and GNUNET\_SYSERR otherwhise. +See listing \ref{lst:crypto-verify-api}. + +\begin{lstlisting}[style=bfh-c,language=C,, caption={GNUnet verify API}, label={lst:crypto-verify-api}] + /** + * Verify whether the given message corresponds to the given signature and the + * signature is valid with respect to the given public key. + * + * @param sig signature that is being validated + * @param pub public key of the signer + * @param msg is the message that should be signed by @a sig (message is used to calculate c) + * @param msg_len is the message length + * @returns #GNUNET_YES on success, #GNUNET_SYSERR if signature invalid + */ + enum GNUNET_GenericReturnValue + GNUNET_CRYPTO_cs_verify (const struct GNUNET_CRYPTO_CsSignature *sig, + const struct GNUNET_CRYPTO_CsPublicKey *pub, + const void *msg, + size_t msg_len); +\end{lstlisting} + +\subsection{Testing} +For digital signature schemes, the most important test case is the \textit{known good} case where a signature is created and successfully validated. +This test case already tests very much in a digital signature scheme. +When the signature creation or verification has a bug, a test will not succeed, because the mathematic operations need to be correct to be validated correctly. + +The cryptographic operations are further tested for deterministicy (where it applies), meaning that multiple function calls with the same input must lead to the same output. + +Since libsodium is used for the finite field arithmetic operations and is a well tested library, many cryptographic tests are already done in libsodium. + +The performance is measured in a benchmark to see how performant \gls{CSBS} are in comparison to the RSA Blind Signature Scheme. + +\section{Taler Cryptographic Utilities} +Taler provides utility functions to support cryptographic operations.\\ +This chapter provides an overview of these utility functions and about the functionality they provide. + +\subsection{Planchet Creation} +In crypto.c many utility functions are provided to create planchets (for planchet details see \ref{fig:coin:states}), blinding secrets and much more. +One difference between \gls{RSABS} and \gls{CSBS} is, that the coin private key and RSA blinding secret can be created at the same point in time, since the RSA blinding secret is created randomly. +However, for Clause Blind Schnorr secrets an additional step is needed, the public $R_0$ and $R_1$ are required to calculate the blinding seed to derive the secrets. + +A planchet in the Clause Blind Schnorr Signature Scheme can be created as followed (implementation details ommited). + +\begin{enumerate} + \item Create planchet with new \ac{EdDSA} private key + \item Derive withdraw nonce + \item Request public $R_0, R_1$ from signer + \item Derive blinding seed + \item Prepare (blind) the planchet +\end{enumerate} + +After the planchet is created, it is sent to the exchange to be signed. + +\subsection{Taler CS Security Module} +The exchange segregates access to the private keys with separate security module processes. +The security module has sole access to the private keys of the online signing keys and thus, only a security module can create signatures. +The different \textit{taler-exchange-secmod} processes (separated by signature scheme) are managing the exchanges online signing keys. The RSA denomination keys for example are managed with \textit{taler-exchange-secmod-rsa}. + +Now a new \textit{taler-exchange-secmod-cs} needs to be created for managing the \gls{CSBS} denomination keys. +These security modules run on the same machine as the httpd process and they use UNIX Domain Sockets as method for \acl{IPC}. +A short introduction about UNIX Domain Sockets can be found in the blog post \cite{matt:unix-domain-sockets}. +Furthermore, the security modules are used to protect the online signing keys by performing the actual signing operations in the dedicated taler-secmod-cs process. +This abstraction makes it harder for an attacker who has already compromised the http daemon to gain access to the private keys. +However, such an attacker would still be able to sign arbitrary messages (see \cite{taler-documentation:exchange-operator-manual}). +A crypto helper exists for each security module, these functions can be called inside the exchange for operations requiring the private online signing keys. +The new Clause Schnorr security module and corresponding crypto helper provides the following functionality: +\begin{itemize} + \item Private Key Management and creation + \item Request public $R_0, R_1$ + \item Request a signature of a $c_0,c_1$ pair + \item Revoke an online signing key +\end{itemize} + +\subsection{Testing} +All of the operations have tests and are included in unit tests. +As a template for testing, the existing RSA tests were used and adjusted for \gls{CSBS}. + + +\section{Denomination Key Management} +Since we introduce a type of denomination keys, related operations like connection to the \gls{CSBS} security module, making the denominations available for customers, persisting them in the database and offline signing using the exchange's offline signature key have to be extended to incorporate the \acl{CS}. + +The exchange offline signer requests the future, not yet signed keys by calling GET \url{/management/keys} as described in table \ref{tab:management-keys-get}. \\\\ +\framebox[1.1\width]{\color{blue}\texttt{GET /management/keys}} +\begin{table}[ht] + \centering + \resizebox{0.9\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{ll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Value} \\ + future\_denoms & Information about denomination keys \\ + future\_signkeys & Information about exchange online signing keys \\ + master\_pub & Exchange's master public key \\ + denom\_secmod\_public\_key & RSA security module public key \\ + denom\_secmod\_cs\_public\_key & \gls{CSBS} security module public key \\ + signkey\_secmod\_public\_key & Online singing security module public key \\ + \end{tabular} + \caption{GET \url{/management/keys} response data} + \label{tab:management-keys-get} +\end{minipage}} +\end{table} + +It then signs the keys and returns them using POST on the same \ac{URL} with the data described in table \ref{tab:management-keys-post}. \\\\ +\framebox[1.1\width]{\color{blue}\texttt{POST /management/keys}} +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{ll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Value} \\ + denom\_sigs & Denomination key signatures \\ + signkey\_sigs & Online signing key signatures \\ + \end{tabular} + \caption{POST \url{/management/keys} response data} + \label{tab:management-keys-post} +\end{table} + +Wallets can then call GET \url{/keys} to obtain the current denominations and other information, the response is described in table \ref{tab:keys-get}. \\\\ +\framebox[1.1\width]{\color{blue}\texttt{GET /keys}} +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{ll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Value} \\ + version & Exchange's protocol version \\ + currency & Currency \\ + master\_public\_key & Exchange's master public key \\ + reserve\_closing\_delay & Delay before reserves are closed \\ + signkeys & Exchange's online signing public keys \\ + recoup & Revoked keys \\ + denoms & List of denominations \\ + auditors & Auditors for this exchange \\ + list\_issue\_date & Timestamp \\ + eddsa\_pub & Exchange's online signing public key \\ + eddsa\_sig & Signature (use "eddsa\_pub" for verification) \\ + \end{tabular} + \caption{GET \url{/keys} response data} + \label{tab:keys-get} +\end{table} + + +\section{New Endpoint for $R$} +The withdraw and refresh protocols using the Claude Blind Schnorr Signature Scheme introduce an additional round trip. +In this round trip, the customer requests two $ R $ from the exchange. +The exchange uses a secret $ r $ to calculate $ R := rG $. +\\ +In contrast to the plain Clause Blind Schnorr Signature Scheme (see \ref{sec:clause-blind-schnorr-sig}), $ r $ isn't generated randomly but instead derived using a \gls{hkdf} with a nonce from the customer and a denomination private key (secret only known by the exchange). +This still ensures that the private $ r $ can't be anticipated, but has multiple advantages regarding \gls{abort-idempotency}. +\Gls{abort-idempotency} means that a withdraw or refresh operation can be aborted in any step and later tried again (using the same values) without yielding a different result. +The challenge for $ r, R $ regarding \gls{abort-idempotency} is to ensure that the same $ r $ is used during the complete signature creation process. + +The only drawback of this process is that we have to ensure that the same nonce and secret aren't used for different withdraw- or refresh-operations. +This is done during signature creation and will be described in the withdraw protocol section \ref{sec:specification-withdraw}. + + +\subsection{Public APIs and Data Structures} +This is a new functionality, meaning a new endpoint accessible to customers has to be introduced. +It will be made available in the exchange HTTP server under \framebox[1.1\width]{\color{blue}\texttt{POST /csr}} and will take the input parameters described in table \ref{tab:csr-request-data} (as \ac{JSON}). +\begin{table}[ht] + \centering + \resizebox{0.9\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + nonce & String & 32 Bytes encoded in Crockford base32 Hex \\ + denom\_pub\_hash & String & Denomination Public Key encoded in Crockford base32 Hex \\ + \end{tabular} + \caption{POST \url{/csr} request data} + \label{tab:csr-request-data} +\end{minipage}} +\end{table} + +The exchange will then check the denomination and return one of these HTTP status codes: +\begin{itemize} + \item \textbf{200 (HTTP\_OK)}: Request Successful + \item \textbf{400 (BAD\_REQUEST)}: Invalid input parameters + \item \textbf{404 (NOT\_FOUND)}: Denomination unknown or not Clause Schnorr + \item \textbf{410 (GONE)}: Denomination revoked/expired + \item \textbf{412 (PRECONDITION\_FAILED)}: Denomination not yet valid +\end{itemize} + +When the request was successful, the exchange returns the data described in table \ref{tab:csr-response-data} (as \ac{JSON}). +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + r\_pub\_0 & String & 32 Bytes encoded in Crockford base32 Hex \\ + r\_pub\_1 & String & 32 Bytes encoded in Crockford base32 Hex \\ + \end{tabular} + \caption{POST \url{/csr} response data} + \label{tab:csr-response-data} +\end{table} + + +\subsection{Persistence} +This API does not persist anything. +This is because the resulting $R_0, R_1$ are derived and can be derived in a later step. + + +\section{Withdraw Protocol} +\label{sec:specification-withdraw} +The withdraw protocol has been introduced in section \ref{sec:withdrawal}. +For the \acl{CS} necessary adjustments are described in section \ref{sec:withdraw-protocol-schnorr}. + + +\subsection{Public APIs and Data Structures} +\label{sec:specification-withdraw-public-api} +The existing endpoint is available under \texttt{POST /reserves/[reserve]/withdraw} where "reserve" is the reserve public key encoded as Crockford base32. +It takes the following input parameters described in table \ref{tab:withdraw-request-data} as JSON.\\\\ +\framebox[1.1\width]{\color{blue}\texttt{POST /reserves/[reserve]/withdraw}} +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{ll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Value} \\ + denom\_pub\_hash & Denomination Public Key \\ + coin\_ev & RSA blinded coin public key \\ + reserve\_sig & Signature over the request using the reserve's private key \\ + \end{tabular} + \caption{Withdraw request data} + \label{tab:withdraw-request-data} +\end{table} + +In order to facilitate parsing, Christian Grothoff suggested to include the cipher type in the "coin\_ev" field, thus creating a nested \ac{JSON} (as described in table \ref{tab:withdraw-coin-ev-rsa}). +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 1 stands for RSA \\ + rsa\_blinded\_planchet & String & RSA blinded coin public key \\ + \end{tabular} + \caption{Withdraw "coin\_ev" field (RSA)} + \label{tab:withdraw-coin-ev-rsa} +\end{table} + +For the Clause Schnorr implementation, the field "rsa\_blinded\_planchet" will be replaced with the necessary values as described in table \ref{tab:withdraw-coin-ev-cs}. +\begin{table}[ht] + \centering + \resizebox{0.85\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 2 stands for \gls{CSBS} \\ + cs\_nonce & String & 32 Bytes encoded in Crockford base32 Hex \\ + cs\_blinded\_c0 & String & 32 Bytes encoded in Crockford base32 Hex \\ + cs\_blinded\_c1 & String & 32 Bytes encoded in Crockford base32 Hex \\ + \end{tabular} + \caption{Withdraw "coin\_ev" field (\gls{CSBS})} + \label{tab:withdraw-coin-ev-cs} +\end{minipage}} +\end{table} + +The exchange will then process the withdraw request and return one of these HTTP status codes: +\begin{itemize} + \item \textbf{200 (HTTP\_OK)}: Request Successful + \item \textbf{400 (BAD\_REQUEST)}: Invalid input parameters (can also happen if denomination cipher doesn't match with cipher in "coin\_ev") + \item \textbf{403 (FORBIDDEN)}: Signature contained in "reserve\_sig" invalid + \item \textbf{404 (NOT\_FOUND)}: Denomination unknown + \item \textbf{410 (GONE)}: Denomination revoked/expired + \item \textbf{412 (PRECONDITION\_FAILED)}: Denomination not yet valid +\end{itemize} + +When the request was successful, the exchange returns the RSA signature as JSON (described in table \ref{tab:withdraw-response-rsa}). +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 1 stands for RSA \\ + blinded\_rsa\_signature & String & RSA signature \\ + \end{tabular} + \caption{Withdraw response (RSA)} + \label{tab:withdraw-response-rsa} +\end{table} + +Table \ref{tab:withdraw-response-cs} describes the response for \gls{CSBS}. +\begin{table}[ht] + \centering + \resizebox{0.85\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 2 stands for \gls{CSBS} \\ + b & Integer & \gls{CSBS} signature session identifier (either 0 or 1) \\ + s & String & signature scalar (32 Bytes encoded in Crockford base32 Hex) \\ + \end{tabular} + \caption{Withdraw response (\gls{CSBS})} + \label{tab:withdraw-response-cs} +\end{minipage}} +\end{table} + + +\subsection{Persistence} +Persistence for withdrawing is implemented in the function \texttt{postgres\_do\_withdraw} in \texttt{src/exchangedb/plugin\_exchangedb\_postgres.c} +For \gls{CSBS}, persisting the blinded signature must be implemented. + + +\section{Deposit Protocol} +For the deposit protocol (described in section \ref{sec:deposit-protocol}) only the handling and verification of \gls{CSBS} signatures has to be added. + +\subsection{Public APIs and Data Structures} +Deposit is an existing endpoint available under \texttt{POST /coins/[coin public key]/deposit} where "coin public key" is encoded as Crockford base32. +Additional parameters are passed as JSON (as described in table \ref{tab:spend-request}).\\\\ +\framebox[1.1\width]{\color{blue}\texttt{POST /coins/[coin public key]/deposit}} +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{ll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Value} \\ + % cipher & Denomination cipher: 2 stands for \gls{CSBS} \\ + % b & \gls{CSBS} signature session identifier (either 0 or 1) \\ + % s & signature scalar (32 Bytes encoded in Crockford base32 Hex) \\ + merchant\_payto\_uri & Account that is credited \\ + wire\_salt & Salt used by the merchant \\ + contribution & Amount to use for payment (for one specific coin) \\ + denom\_pub\_hash & Denomination public key hash \\ + ub\_sig & (unblinded) denomination signature of coin \\ + merchant\_pub & Merchant public key \\ + h\_contract\_terms & Contract terms hash \\ + coin\_sig & Deposit permission signature \\ + timestamp & Timestamp of generation \\ + refund\_deadline (optional) & Refund deadline \\ + wire\_transfer\_deadline (optional) & Wire transfer deadline \\ + \end{tabular} + \caption{Spend request} + \label{tab:spend-request} +\end{table} + +Relevant field for the \gls{CSBS} implementation is the field "ub\_sig" containing the unblinded denomination signature of the coin. +For RSA, the (nested) \ac{JSON} is described in table \ref{tab:spend-request-ubsig-rsa}. +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 1 stands for RSA \\ + rsa\_signature & String & Unblinded RSA signature \\ + \end{tabular} + \caption{ub\_sig (RSA)} + \label{tab:spend-request-ubsig-rsa} +\end{table} + +Table \ref{tab:spend-request-ubsig-cs} describes the values in "ub\_sig" required for \gls{CSBS}. +\begin{table}[ht] + \centering + \resizebox{0.85\textwidth}{!}{\begin{minipage}{\textwidth} + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Field} & \textbf{Type} & \textbf{Value} \\ + cipher & Integer & Denomination cipher: 2 stands for \gls{CSBS} \\ + cs\_signature\_r & String & Curve point $ R' $ (32 Bytes encoded in Crockford base32 Hex) \\ + cs\_signature\_s & String & Signature scalar (32 Bytes encoded in Crockford base32 Hex) \\ + \end{tabular} + \caption{ub\_sig (\gls{CSBS})} + \label{tab:spend-request-ubsig-cs} +\end{minipage}} +\end{table} + + +\subsection{Persistence} +Persistence is handled in the functions \texttt{postgres\_insert\_deposit} and\\ \texttt{postgres\_have\_deposit} located in \url{src/exchangedb/plugin_exchangedb_postgres.c}. +However, these functions are not containing \gls{CSBS}-specific persistence. +\\What needs to be adjusted however, is the function \texttt{postgres\_ensure\_coin\_known} called by the function \texttt{TEH\_make\_coin\_known} (located in \url{src/exchange/taler-exchange-httpd_db.c}). + + +% \section{Tipping} +% \subsection{Public APIs and Data Structures} +% \subsection{Code Location} +% \subsection{Persistence} +% \subsection{Used Libraries} + +% \section{Payback Protocol} +% \subsection{Public APIs and Data Structures} +% \subsection{Code Location} +% \subsection{Persistence} +% \subsection{Used Libraries} + + +% sollte ein Product Backlog das Ziel dieser Phase sein? diff --git a/doc/cs/content/4_3_implementation.tex b/doc/cs/content/4_3_implementation.tex new file mode 100644 index 000000000..07423e4e1 --- /dev/null +++ b/doc/cs/content/4_3_implementation.tex @@ -0,0 +1,333 @@ +\chapter{Implementation} +\label{chap:implement} +This chapter gives an overview on the implementation challenges and discusses special parts in the implementation. + + +\section{Signature Scheme Operations} +The signature scheme operations are implemented in the GNUnet core repository \cite{gnunet-git} (and have been merged into the master branch). +This would allow other GNUnet projects to use our implementation of the Clause Blind Schnorr Signature Scheme. + +The implementation is done in multiple locations: +\begin{itemize} + \item \texttt{src/include/gnunet\_crypto\_lib.h}: + This header file is included when using GNUnet's cryptography implementation. + \item \texttt{src/util/crypto\_cs.c}: + The functions specified in \texttt{gnunet\_crypto\_lib.h} will be implemented here. + \item \texttt{src/util/test\_crypto\_cs.c}: + The test cases for the signature scheme will be implemented here. + \item \texttt{src/util/perf\_crypto\_cs.c}: + This file houses the implementation of a small program that will be used to compare the performance against the blind RSA Signature Scheme. +\end{itemize} + +The specification explaining the \ac{API} can be found in section \ref{sec:specification-signature-scheme}. There are two internal functions that have to be explained further in this section. + +The \texttt{map\_to\_scalar\_subgroup} function clamps scalars, which is necessary for values that are derived using a \gls{hkdf}. +It sets the three least significant bits to zero (making the scalar a multiple of 8), sets the most significant bit to zero and the second-most significant bit to one. +This process is further described in \cite{rfc7748} and \cite{madden:curve25519-clamping}. + +\begin{lstlisting}[style=bfh-c, language=C, caption={Function map\_to\_scalar\_subgroup - Crypto API}, label={lst:map-to-scalar}] +static void +map_to_scalar_subgroup (struct GNUNET_CRYPTO_Cs25519Scalar *scalar) +{ + scalar->d[0] &= 248; + scalar->d[31] &= 127; + scalar->d[31] |= 64; +} +\end{lstlisting} + +Another important function is the \gls{fdh} (see \ref{sec:schnorr-sig}) used to map the message to a scalar. +GNUnet provides a \gls{fdh} function, which expects libgcrypt's multi precision format. +A conversion function is provided by GNUnet, which requires the data to be in big endian format. +Since libsodium uses a little endian representation, the conversion process must include endianness conversion. +The complete \gls{fdh} including the required conversions is implemented in the function described in listing \ref{lst:cs-fdh}. +\begin{lstlisting}[style=bfh-c, language=C, caption={Function cs\_full\_domain\_hash - Crypto API}, label={lst:cs-fdh}] +static void +cs_full_domain_hash (const struct GNUNET_CRYPTO_CsRPublic *r_dash, + const void *msg, + size_t msg_len, + const struct GNUNET_CRYPTO_CsPublicKey *pub, + struct GNUNET_CRYPTO_CsC *c) +{ + ... +\end{lstlisting} + +Last but not least, the implementation has one notable performance improvement not mentioned in the redesigned protocols. +In various steps \gls{hkdf} is used multiple times in a row. +For example to derive the four blinding secrets $\alpha_0, \alpha_1, \beta_0, \beta_1$. +The derivation can be done in one \gls{hkdf} call with bigger output size, 128 bit in this case. +The output then can be split in four parts and then mapped to the ed25519 subgroup. +This can be done secure, because as explained in \autoref{sec:kdf} a \gls{hkdf} output is truly random. + + +\section{Taler Cryptographic Utilities} +\begin{bfhNoteBox} + Implementation is done in Taler's exchange. + From here on the implementation can be found in the exchange git repository \cite{taler-git:exchange}. +\end{bfhNoteBox} +The cryptographic utilities of Taler can be found in \texttt{src/util}. + + +The implementation is done in various locations: +\begin{itemize} + \item \texttt{src/include/taler\_crypto\_lib.h}: This header file is included when using Taler's cryptography implementation. + The different data structures and functionality are defined here. + \item \texttt{src/util/denom.c}: Implement denomination utility functions for \gls{CSBS} cases + \item \texttt{src/util/crypto.c}: Adjust all utility functions to support \gls{CSBS}. + crypto.c contains many cryptographic utility functions, for example to create planchets or blinding factors. + \item \texttt{src/util/test\_crypto.c}: Functionality tests for crypto.c and denom.c + \item \texttt{src/include/taler\_signatures.h}: In this header file message formats and signature constants are defined (not modified) + \item \texttt{src/util/secmod\_signatures.c}: Utility functions for Taler security module signatures +\end{itemize} + +The security module \texttt{taler-secmod-cs} is implemented here: +\begin{itemize} + \item \texttt{src/util/taler-exchange-secmod-cs.c}: Standalone process to perform private key Clause Blind Schnorr signature operations. + \item \texttt{src/util/taler-exchange-secmod-cs.h}: Specification of \ac{IPC} messages for the CS secmod process + \item \texttt{src/util/taler-exchange-secmod-cs.conf}: Configuration file for the secmod process + \item \texttt{src/util/secmod\_common.c} and \texttt{src/util/secmod\_common.h}: Common functions for the exchange's security modules (not modified) +\end{itemize} + +The corresponding crypto helper, that talks with the security module, and its tests \& benchmarks are implemented here: +\begin{itemize} + \item \texttt{src/util/crypto\_helper\_cs.c}: Utility functions to communicate with the security module + \item \texttt{src/util/crypto\_helper\_common.c}: and \texttt{crypto\_helper\_common.h}: Common functions for the exchange security modules (not modified) + \item \texttt{src/util/test\_helper\_cs.c}: Tests and benchmarks for the \gls{CSBS} crypto helper +\end{itemize} +% Crypto API offene Punkte: +%Input-Validierung von Punkten und Skalar +% Clamping beschreiben: https://neilmadden.blog/2020/05/28/whats-the-curve25519-clamping-all-about/ +% Testing: inverse operations, blinded signature test + + +\section{Denomination Key Management} +For the implementation, the \gls{CSBS} security module had to be connected to the key handling and the \gls{CSBS} denominations had to be integrated: +\begin{itemize} + \item \url{src/exchange/taler-exchange-httpd_keys.h} and \\ + \url{src/exchange/taler-exchange-httpd_keys.c}: Integrate \gls{CSBS} secmod and denomination key management + \item \url{src/exchange-tools/taler-exchange-offline.c}: Implement \gls{CSBS} case for offline signing of denomination keys + \item \url{src/include/taler_exchange_service.h}: \\ + Add \gls{CSBS} secmod public key to struct\\TALER\_EXCHANGE\_FutureKeys + \item \url{src/json/json_helper.c}: Implement CS case in function parse\_denom\_pub (used in taler-exchange-offline.c) + \item \url{src/json/json_pack.c}: Implement \gls{CSBS} case in function TALER\_JSON\_pack\_denom\_pub (used in taler-exchange-httpd\_keys.c) + \item \url{src/pq/pq_query_helper.c}: Implement \gls{CSBS} case in function qconv\_denom\_pub + \item \url{src/pq/pq_result_helper.c}: Implement \gls{CSBS} case in function extract\_denom\_pub +\end{itemize} + +In order for the tests to pass, the following changes had to be implemented: +\begin{itemize} + \item \url{src/lib/exchange_api_management_get_keys.c}: Add denom\_secmod\_cs\_public\_key JSON parsing, implement \gls{CSBS} case \\in function TALER\_EXCHANGE\_ManagementGetKeysHandle + \item \url{src/testing/.gitignore}: Add paths where \gls{CSBS} keys are stored (secmod-helper) + \item \url{src/testing/test_auditor_api.conf}: Add section taler-exchange-secmod-cs + \item \url{src/testing/test_exchange_api_keys_cherry_picking.conf}: Add section taler-exchange-secmod-cs + \item \url{src/testing/testing_api_helpers_exchange.c}: Add \gls{CSBS} secmod start and stop logic +\end{itemize} + + +\section{New Endpoint for $R$} +The new endpoint is available in the exchange's HTTP server under \url{/csr}. +It parses and checks the input, passes the request for derivation of the two $ R $'s down to the \gls{CSBS} security module and returns them to the requestor. +The implementation can be found in: +\begin{itemize} + \item \url{src/exchange/taler-exchange-httpd.c}: + Definition for the new endpoint, calls the function that handles \url{/csr} requests + \item \url{src/exchange/taler-exchange-httpd_responses.h} and \\ + \url{src/exchange/taler-exchange-httpd_responses.c}: \\ + Added function TEH\_RESPONSE\_reply\_invalid\_denom\_cipher\_for\_operation that indicates a failure when the endpoint is called for a non-\gls{CSBS} denomination + \item \url{src/exchange/taler-exchange-httpd_csr.h} and \\ + \url{src/exchange/taler-exchange-httpd_csr.c}: \\ + Implementation of the request handler for the new endpoint + \item \url{src/exchange/taler-exchange-httpd_keys.h} and \\ + \url{src/exchange/taler-exchange-httpd_keys.c}: \\ + Additional function TEH\_keys\_denomination\_cs\_r\_pub that passes down the request to derive the $ R $ to the taler-exchange-secmod-cs helper +\end{itemize} + +The tests that check the functionality of the procotols are defined in \url{src/testing/} and use code that calls the \ac{API} (located in \url{src/lib/}). +Since the new endpoint is used during withdrawing coins, testing for the \url{/csr} endpoint is integrated in these protocol tests. +Therefore, a call to the endpoint was implemented and later integrated into the calls to the withdraw-\ac{API}. +Code for calling the endpoint is located in these files: +\begin{itemize} + \item \url{src/include/taler_exchange_service.h}: \\ + Header describing functions and data structures used in withdraw and refresh testing: + \begin{itemize} + \item struct TALER\_EXCHANGE\_CsRHandle: Handle containing request information + \item struct TALER\_EXCHANGE\_CsRResponse: Response details + \item function TALER\_EXCHANGE\_CsRCallback: Callback function to deliver the results (used in withdraw and refresh) + \item function TALER\_EXCHANGE\_csr: Used to call endpoint + \item function TALER\_EXCHANGE\_csr\_cancel: Used to free dynamically allocated resources + \end{itemize} + \item \url{src/lib/exchange_api_csr.c}: Implementation of \url{/csr} request +\end{itemize} + + +\section{Withdraw Protocol} +\label{sec:withdraw-protocol-impl} +Since this is an existing endpoint, it was adjusted to support \gls{CSBS}. +Mainly, the in- and output-handling had to be adjusted as described in section \ref{sec:specification-withdraw-public-api}, additional cipher checks for the denomination were added and the \gls{CSBS} for persisting the request in the database was implemented. +\\\\ +An interesting part of the implementation is the check whether a nonce was already used for this denomination or not (step: $s \leftarrow \text{GetWithdraw}(n_w, D_p)$). +This step ensures that the same signature will always be returned for a certain nonce. +Using the same nonce for the same denomination twice without this check would lead to the same random value $r$. +This is due to derivation of $r := \text{HKDF}(256,n_w || d_s, \text{"r"})$. +An attacker could then immediately recover the secret key by the following equation: $(h' - h) * x \mod q = s -s' \mod q$ \cite{tibouchi:attacks-schnorr-nonce}. +There are popular examples of this vulnerability in Sony Playstation 3's or Bitcoins ECDSA implementation \cite{buchanan:ps3-ecdsa-vuln} \cite{wang:bitcoin-ecdsa-vuln}. +More details on how such a vulnerability can be exploited can be found in one of the author's blog posts \cite{gian:nonce-sense}.\\ +The designed Taler protocols using \gls{CSBS} are preventing this attack by checking the nonce and return the previously generated signature. +Additionally the denomination's public key is included in this check to prevent another issue explained in section \ref{sec:taler-vuln}.\\ +The check is implemented by persisting a hash value over $n_w$ and $D_p$. +On every withdrawal \texttt{check\_request\_idempotent()} is called, which checks whether the persisted hash matches with the current $n_w, D_p$ pair. + + +\begin{itemize} + \item \url{src/exchange/taler-exchange-httpd_withdraw.c}: Implementation of \gls{CSBS} case for withdraw endpoint + \item \url{src/exchange/taler-exchange-httpd_keys.c}: Implement \gls{CSBS} case in function \\ + TEH\_keys\_denomination\_sign (passes the signature creation down to the crypto helpers) + \item \url{src/include/taler_json_lib.h} and \url{src/json/json_helper.c}: \\ + Add function TALER\_JSON\_spec\_blinded\_planchet + \item \url{src/json/json_pack.c}: \\ + Implement \gls{CSBS} case in function\\ TALER\_JSON\_pack\_blinded\_denom\_sig + \item \url{src/pq/pq_query_helper.c}: implement \gls{CSBS} case in functions qconv\_denom\_sig and qconv\_blinded\_denom\_sig + \item \url{src/pq/pq_result_helper.c}: Implement \gls{CSBS} case in function extract\_blinded\_denom\_sig +\end{itemize} + +For testing, the \gls{CSBS}-related data structures and procedures as well as the request to the additional endpoint \url{/csr} (before performing the actual withdrawal) were integrated: +\begin{itemize} + \item \url{src/testing/test_exchange_api.c}: Add additional tests for \gls{CSBS} withdraw + \item \url{src/include/taler_testing_lib.h}: Specification for functions \\ + TALER\_TESTING\_cmd\_withdraw\_cs\_amount and \\ + TALER\_TESTING\_cmd\_withdraw\_cs\_amount\_reuse\_key, add denomination cipher parameter to function TALER\_TESTING\_find\_pk + \item \url{src/testing/testing_api_cmd_withdraw.c}: add functions \\ + TALER\_TESTING\_cmd\_withdraw\_cs\_amount and \\ + TALER\_TESTING\_cmd\_withdraw\_cs\_amount\_reuse\_key, implement \gls{CSBS}-specific logic for withdraw + \item \url{src/testing/testing_api_helpers_exchange.c}: + add cipher parameter to function TALER\_TESTING\_find\_pk + \item \url{src/lib/exchange_api_withdraw.c}: Implement \gls{CSBS}-specific withdraw logic, integrate \url{/csr} request + \item \url{src/lib/exchange_api_withdraw2.c}: implement \gls{CSBS} case + \item \url{src/include/taler_json_lib.h} and \url{src/json/json_pack.c}: \\ + Add function TALER\_JSON\_pack\_blinded\_planchet + \item \url{src/json/json_helper.c} implement \gls{CSBS} case in function parse\_blinded\_denom\_sig +\end{itemize} + +\section{Deposit Protocol} +For deposit, only few changes were necessary because some of the required functionality has already been added for the previously implemented protocols, and only the coin signature verification is \gls{CSBS}-specific in this protocol. +\begin{itemize} + \item \url{/src/exchange/taler-exchange-httpd_deposit.c}: Add check whether denomination cipher and denomination signature cipher are equal + \item \url{/src/json/json_helper.c}: Implement \gls{CSBS} case in function parse\_denom\_sig + \item \url{/src/pq/pq_result_helper.c}: Implement \gls{CSBS} case in function extract\_denom\_sig +\end{itemize} + +Tests for deposit are implemented here: +\begin{itemize} + \item \url{/src/testing/test_exchange_api.c}: Add tests (see "struct TALER\_TESTING\_Command\ spend\_cs[]") that spend \gls{CSBS} coins withdrawn in tests added for withdrawal + \item \url{/src/json/json_pack.c}: Implement \gls{CSBS} case in function TALER\_JSON\_pack\_denom\_sig +\end{itemize} + +\section{Fixing a Minor Security Issue in Taler's RSA Blind Signature Protocols} +\label{sec:taler-vuln} +While implementing the nonce check in the \gls{CSBS} protocol (see section \ref{sec:withdraw-protocol-impl}), a minor security issue in Taler's current RSA Blind Signature implementation was detected and fixed. +The issue was only in the implementation of the current RSA Blind Signature protocols, the fix for this scenario was already implemented in \gls{CSBS} since the beginning. + +\subsection{Security Issue} +\label{sec:taler-vuln-desc} + +The redesigned \gls{CSBS} protocols already include the denomination key in the nonce check, which fixes this issue (see \ref{sec:withdraw-protocol-schnorr}). +In the case of \gls{RSABS}, the current protocol includes an \gls{idempotence} check by persisting the hash value of the blinded coin $m'$. +On a withdrawal/refresh the \gls{idempotence} check compares if the hash value of $m'$ was seen in the past and returns the 'old' signature on a match. +This could lead to the following scenario: + +\begin{enumerate} + \item A broken wallet withdraws a coin with denomination $D_{p_{(1)}}$. + \item The wallet sends a request to withdraw the same coin for denomination $D_{p_{(2)}}$. + \item The exchange returns the signature for the denomination $D_{p_{(1)}}$ due to the \gls{idempotence} check. + \item Since the exchange returned an invalid signature, the customer can file a complaint at the auditor. + \item The auditor then has to investigate why the exchange returned invalid signatures. + \item The auditor can disprove the complaint by querying the persisted hash used for the \gls{idempotence} check. + With the associated denomination public key that is also persisted, the auditor can successfully verify the signature and thus prove that the exchange operated honestly. +\end{enumerate} + +Including the denomination public key into the persisted hash for the \gls{idempotence} check solves this issue. +If a broken wallet now sends the same coin for more than one denomination, the exchange returns valid signatures in both cases.\\ +While this is still an issue, this case is already handled nicely in Taler since this situation could also occur if a broken value tries to withdraw the same coin with two different blinding factors. + +\subsection{Impact} +The impact of this security vulnerability is considered as very low. +An auditor investigating such an issue can simply retrace what happened by checking the persisted hash and associated denomination. +The impact of the issue is, that an auditor needs to investigate an issue, which can be prevented inside the protocol. +\\ +In the previous section the client was considered a broken wallet. +While this could be done on purpose by malicious a customer, there is no real motivation for abusing this issue due the easy detection of an auditor. + + +\subsection{Fix} +Listing \ref{lst:rsa-idempotence} shows the code of calculating the hash for the idempotency check in the RSA case before it was fixed. +By trying to implement the \gls{CSBS} case, the question came up why the RSA case has not included the denomination key into the check. +After discussing this issue with Christian Grothoff, the conclusion was to include the denomination public key to prevent the discussed issue. + +\begin{lstlisting}[style=bfh-c,language=C, caption={Idempotency check on RSA}, label={lst:rsa-idempotence}] + enum GNUNET_GenericReturnValue + TALER_coin_ev_hash (const struct TALER_BlindedPlanchet *blinded_planchet, + struct TALER_BlindedCoinHash *bch) + { + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + GNUNET_CRYPTO_hash ( + blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size, + &bch->hash); + return GNUNET_OK; + case TALER_DENOMINATION_CS: + ... + +\end{lstlisting} + +The issue is fixed by adding a hash of the current denomination key into the calculation of the hash used in the \gls{idempotence} check. +The applied fix can be seen in listing \ref{lst:fixed-idempotence}. + +\begin{lstlisting}[style=bfh-c,language=C, caption={Fixed idempotency check}, label={lst:fixed-idempotence}] + enum GNUNET_GenericReturnValue + TALER_coin_ev_hash (const struct TALER_BlindedPlanchet *blinded_planchet, + const struct TALER_DenominationHash *denom_hash, + struct TALER_BlindedCoinHash *bch) + { + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + { + struct GNUNET_HashContext *hash_context; + hash_context = GNUNET_CRYPTO_hash_context_start (); + + GNUNET_CRYPTO_hash_context_read (hash_context, + &denom_hash->hash, + sizeof(denom_hash->hash)); + GNUNET_CRYPTO_hash_context_read (hash_context, + blinded_planchet->details. + rsa_blinded_planchet.blinded_msg, + blinded_planchet->details. + rsa_blinded_planchet.blinded_msg_size); + GNUNET_CRYPTO_hash_context_finish (hash_context, + &bch->hash); + return GNUNET_OK; + } + case TALER_DENOMINATION_CS: + { + struct GNUNET_HashContext *hash_context; + hash_context = GNUNET_CRYPTO_hash_context_start (); + + GNUNET_CRYPTO_hash_context_read (hash_context, + &denom_hash->hash, + sizeof(denom_hash->hash)); + GNUNET_CRYPTO_hash_context_read (hash_context, + &blinded_planchet->details. + cs_blinded_planchet.nonce, + sizeof (blinded_planchet->details. + cs_blinded_planchet.nonce)); + GNUNET_CRYPTO_hash_context_finish (hash_context, + &bch->hash); + return GNUNET_OK; + } + default: + GNUNET_break (0); + return GNUNET_SYSERR; + } + } +\end{lstlisting} diff --git a/doc/cs/content/4_execution.tex b/doc/cs/content/4_execution.tex new file mode 100644 index 000000000..675a33439 --- /dev/null +++ b/doc/cs/content/4_execution.tex @@ -0,0 +1,5 @@ +\input{content/4_1_design.tex} + +\input{content/4_2_specification.tex} + +\input{content/4_3_implementation.tex} diff --git a/doc/cs/content/5_discussion.tex b/doc/cs/content/5_discussion.tex new file mode 100644 index 000000000..1e1bcd5d7 --- /dev/null +++ b/doc/cs/content/5_discussion.tex @@ -0,0 +1,317 @@ +\chapter{Discussion} +\label{chap:disc} +This chapter analyses the \acl{CS} implementation and compares it to the existing implementation with \gls{RSABS}. +The comparison will include the schemes itself, performance comparisons and a discussion on the security assumptions. +For the performance comparison CPU usage, latency, bandwidth and storage space are compared. + +\section{Cipher Agility} +One of the benefits of having another blind signature scheme in Taler is \textit{cipher agility}. +Cipher agility means that one scheme can substitute another, for example if one scheme gets compromised in the future. + +Cipher agility is considered harmful in certain situations. +TLS 1.2 \cite{rfc5246} and IPSEC/IKEv2 \cite{rfc6071} are good examples on how dangerous cipher agility inside protocols can be. +There are many ways these protocols can be set up insecure. +\\\\ +Taler's protocols are built around blind signature schemes. +Therefore it is crucial to have an additional secure blind signature scheme that works with all Taler protocols. +As described in section \ref{sec:blind-sign-schemes}, blind signature schemes can vary and may be complex to substitute. +The \gls{CSBS} implementation provides such an alternative and thus \textit{cipher agility}. + +\section{Scheme Comparison} +\label{chap:disc-scheme-comp} +Both schemes are explained in the preliminaries chapter (\gls{RSABS} in section \ref{fig:rsa-fdh-blind-sign} and \gls{CSBS} in \ref{fig:clause-blind-schnorr-sign-scheme}). +\\ +There are multiple differences worth mentioning. +The first difference is that Schnorr signatures are inherently randomized. +This is also where the additional step in Schnorr signatures comes from. +A random number is chosen by the signer for every signature. \\ +In \gls{CSBS} two blinding secrets are used instead of one in \gls{RSABS}. +On top of that, \gls{CSBS} needs to do most computations for signature creation twice, due to the \ac{ROS} problem (see \ref{par:ros-problem}). +\\\\ +\textit{\Gls{abort-idempotency}} is a very important property for Taler. +Ensuring \gls{abort-idempotency} with the \gls{CSBS} scheme is harder than it was with RSA, due to the many random elements in the scheme ($r_0, r_1, \alpha_0, \alpha_1, \beta_0, \beta_1, b$). +The reason that these values are chosen randomly is the need for \textit{unpredictability}.\\ +In the protocols (see chapter \ref{chap:design}) \gls{hkdf} is extensively used to derive these values instead of randomly generating them. +That way, the values are still \textit{unpredictable} (due to \gls{hkdf} properties), but now the protocols also ensure \textit{\gls{abort-idempotency}}. +In comparison to the RSA Blind Signature scheme, this is a clever and elegant solution, but the protocol complexity is increased. +\\\\ +One could now think that RSA would be much simpler to implement, since the scheme looks easier and more accessible for many. +This can go horribly wrong and many developers still underestimate implementing RSA. +There are a lot of attacks on RSA, some examples are listed on the famous tool RsaCtfTool \cite{ganapati:rsactftool}. +Ben Perez made a popular talk and blog post, about why one should stop using RSA and should preferably use libsodium and \ac{ECC} \cite{perez:stoprsa}. +Using \gls{RSABS} in Taler is still a reasonable and fine choice. +Taler uses libgcrypt, a well-known and tested library. +\\ +To conclude, the \gls{CSBS} protocols might be more complex to understand than the RSA Blind Signature protocols. +One has to keep in mind that implementing RSA correctly is hard. +\\ +Another difference worth mentioning is, that the \gls{CSBS} scheme does not need scheme specific configurations, whereas RSA needs a key size specified. +This is because the implemented \gls{CSBS} version only supports \gls{25519}. +\\\\ +Furthermore, both schemes provide \textit{perfect blindness}, see paragraph \ref{par:prop-blindness-rsa} for RSA and paragraph \ref{par:prop-blindness-cs} for \gls{CSBS}. + + +\section{Performance Comparison} +\label{sec:disc-perf-comp} +This section compares how the two schemes perform regarding CPU usage, latency, bandwidth and space. +Clause Schnorr has fixed key sizes with 256 bits (32 bytes), which we compare against different RSA key sizes (1024, 2048, 3072 and 4096 bits). +In terms of security, \gls{CSBS} 256 bit keys could be compared to 3072 bit RSA keys (see \url{https://www.keylength.com/} for more information). + +\subsection{CPU Usage} +Various benchmarks were made on different CPU architectures. +This section discusses the main results, detailed information about the performance comparison can be found in appendix \ref{chap:app-perf}. +We thank the Taler team for providing measurements from additional systems and architectures. + +Table \ref{tab:comp-cs-vs-rsa-3072} shows how \gls{CSBS} compares to RSA 3072. +RSA 3072 was chosen for comparison, since they both provide a comparable level of security. +Both provide about 128 bits of security, which means that roughly $2^{128}$ attempts in average are needed for a successful brute-force attack.\\ +The table shows that \gls{CSBS} has better performance compared to RSA 3072 in all operations. +The biggest difference can be seen in the key generation. +In RSA, two random primes are needed, whereas \ac{DLP} algorithms like \gls{CSBS} only need to generate a random value. +Since key generation is done rarely compared to the other operations, the time needed for key generation does not matter that much.\\ +Furthermore, the blinding in \gls{CSBS} is still faster than blinding in RSA, although in the \gls{CSBS} case the calculation is done twice. Also the derivation of $r_0,r_1$, the generation of $R_0,R_1$ and the derivation of $\alpha_0, \beta_0, \alpha_1, \beta_1$ is included in the measurement for the blinding operation of \gls{CSBS}. +Signing and blinding operations are much faster in \gls{CSBS}, also \gls{CSBS} signature verification is faster than RSA 3072. + +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core AMD Ryzen 7 PRO 5850U \\ + OS: Ubuntu 21.10 Linux 5.13.0-25-generic \#26-Ubuntu SMP Fri Jan 7 15:48:31 UTC 2022 x86\_64 x86\_64 x86\_64 GNU/Linux \\ + libsodium version: 1.0.18-1build1 \\ + libgcrypt version: 1.8.7-5ubuntu2 \\\\ + Benchmarks with other hardware setups can be found in appendix \ref{chap:app-perf}. +\end{bfhBox} + +\begin{table}[h] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.204 ms \\\hline + RSA 3072 bit & 10x key generation & 2684 ms \\\hline + \hline + CS & 10x derive $R_0, R_1$ \& blinding & 3.870 ms \\\hline + RSA 3072 bit & 10x blinding & 5 ms \\\hline + \hline + CS & 10x signing & 0.077 ms \\\hline + RSA 3072 bit & 10x signing & 86 ms \\\hline + \hline + CS & 10x unblinding & 0.001 ms \\\hline + RSA 3072 bit & 10x unblinding & 24 ms \\\hline + \hline + CS & 10x verifying & 1.358 ms \\\hline + RSA 3072 bit & 10x verifying & 3.075 ms \\\hline + \end{tabular} + \caption{Comparison on CS vs. RSA 3072} + \label{tab:comp-cs-vs-rsa-3072} +\end{table} + +Table \ref{tab:comp-cs-vs-rsa-1024} shows a comparison between \gls{CSBS} and RSA 1024 bit. +RSA 1024 is in some situations faster than the \gls{CSBS} implementation. +Note that 1024 bit keys are not recommended for many use cases, but the highest currently known RSA factorization done is 829 bits \cite{enwiki:1055393696}. +The following section \ref{sec:disc-risk} explains the risk running RSA 1024 or \gls{CSBS} denominations further.\\ +The blind and unblind operations are running in a wallet implementation, therefore the comparison with RSA 1024 is very interesting for devices with less CPU power. +Comparison of such hardware can be found in appendix \ref{chap:app-perf}, these comparison results come to the same conlcusion.\\ +Although RSA 1024 bit is much faster in the blinding operation, \gls{CSBS} still perform better when calculating the blinding and unblinding operations together. +\gls{CSBS} unblinding computes only an addition of two scalars $s + \alpha \mod p$, while RSA computes $s * r^{-1}$. +To conclude, \gls{CSBS} are faster than RSA 1024 bit and provide a better level of security. +This can be especially useful for wallets running on devices with less CPU power. +The verification on RSA 1024 is faster than \gls{CSBS}. +Therefore, it has to be further investigated which algorithm would overall perform better for the exchange or merchants. +While RSA 1024 bit can compete in certain operations, \gls{CSBS} provide a better level of security and are still faster in most operations. + +\begin{table}[h] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.204 ms \\\hline + RSA 1024 bit & 10x key generation & 126 ms \\\hline + \hline + CS & 10x derive $R_0, R_1$ \& blinding & 3.870 ms \\\hline + RSA 1024 bit & 10x blinding & 1.282 ms \\\hline + \hline + CS & 10x signing & 0.077 ms \\\hline + RSA 1024 bit & 10x signing & 7 ms \\\hline + \hline + CS & 10x unblinding & 0.001 ms \\\hline + RSA 1024 bit & 10x unblinding & 2.991 ms \\\hline + \hline + CS & 10x verifying & 1.358 ms \\\hline + RSA 1024 bit & 10x verifying & 0.876 ms \\\hline + \end{tabular} + \caption{Comparison on CS vs RSA 1024} + \label{tab:comp-cs-vs-rsa-1024} +\end{table} +\subsection{Disk Space} +\begin{bfhWarnBox} + These are theoretical calculations, implementations may choose to persist additional values. + \end{bfhWarnBox} +\gls{CSBS} save disk space due to the much smaller key sizes. +Even more disk space is saved by deriving values with the \gls{hkdf}, these values do not have to be stored. +\\ +Table \ref{tab:comp-sign-space} shows the disk space comparison of signatures, the private keys alone need even less space with 256 bits per key. +\\ +The wallet saves a lot of disk space by deriving most of the values. +In the \gls{CSBS} case a wallet must at least persist the private key $c_s$, $R_0, R_1, s', D_p$, each being 256 bits (32 bytes). +A wallet needs to persist 150 bytes per coin in total. +In the RSA Blind Signature case the wallet persists $c_s$, $b$, $\sigma_c$, $D_p$. +\\Note: for refreshed coins an additional 32 byte value is persisted as seed.\\ +$c_s$ is still a 32 byte value in the RSA case, the other values depend on the RSA key size. (32 byte + 3 * \textit{rsa\_keysize}). +The disk space comparison for a wallet can be found in \ref{tab:comp-wallet-space}. + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lccr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Disk Space} & \textbf{Factor} & \textbf{Disk Space 1M signatures}\\\hline + CS & 512 bits & 1x & 64 MB\\\hline + RSA 1024 bit & 1024 bits & 2x & 128 MB \\\hline + RSA 2048 bit & 2048 bits & 4x & 256 MB\\\hline + RSA 3072 bit & 3072 bits & 6x & 384 MB\\\hline + RSA 4096 bit & 4096 bits & 8x & 512 MB\\\hline + \end{tabular} + \caption{Comparison disk space signatures} + \label{tab:comp-sign-space} +\end{table} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lccr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Disk Space} & \textbf{Factor} & \textbf{Disk Space 1M coins}\\\hline + CS 256 bits & 150 bytes & 1x & 150 MB\\\hline + RSA 1024 bit & 416 bytes & 2.7x & 416 MB \\\hline + RSA 2048 bit & 800 bits & 5.3x & 800 MB\\\hline + RSA 3072 bit & 1184 bits & 7.9x & 1184 MB\\\hline + RSA 4096 bit & 1568 bits & 10.4x & 1568 MB\\\hline + \end{tabular} + \caption{Comparison disk space wallet} + \label{tab:comp-wallet-space} +\end{table} + +\subsection{Bandwidth} +\begin{bfhWarnBox} + These are theoretical calculations, implementations may choose to persist additional values. +\end{bfhWarnBox} +The reasons that \gls{CSBS} use less bandwidth is mostly because the signature/key sizes are much smaller. +The bandwith improvements for the \texttt{/keys} API is the same as specified in the table with disk space comparison \ref{tab:comp-sign-space}. +For \gls{CSBS} many calculations are performed twice, therefore also two values are submitted. +Table \ref{tab:comp-band-withd} compares the bandwidth used in a withdrawal. +The 32 byte values $2 * n_w, 2 * D_p, R_0, R_1, s,W_p, c_0, c_1, \sigma_W$ as well as an integer $b$ are transmitted for \gls{CSBS}.\\ +For RSA, the values $D_p, m', \sigma'_c$ have the same size as the key size. +Additionally, the 32 byte values $W_p, \sigma_W$ are transmitted. +\\\\ +In the refresh protocol the only difference is an additional hash ($h_{C_0}, h_{C_1}$ instead of only $h_C$) sent in the commit phase. +Depending on the hash size another 32 byte (or 64 byte) value is transmitted. + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lccr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Bandwith used} & \textbf{Factor} & \textbf{1M coins}\\\hline + CS 256 bits & 356 bytes & 1x & 324 MB\\\hline + RSA 1024 bit & 448 bytes & 1.3x & 448 MB \\\hline + RSA 2048 bit & 832 bits & 2.5x & 832 MB\\\hline + RSA 3072 bit & 1216 bits & 3.75x & 1216 MB\\\hline + RSA 4096 bit & 1600 bits & 4.9x & 1600 MB\\\hline + \end{tabular} + \caption{Bandwith comparison withdrawal} + \label{tab:comp-band-withd} +\end{table} + +\subsection{Latency} +This section the notion of \acl{RTT} (see \cite{geeks:rtt}) is used. +There are many factors that influence the measurement of a \acl{RTT}. +Following factors can bring huge changes in the value of \ac{RTT}s. +\begin{itemize} + \item Distance + \item Transmission medium + \item Network hops + \item Traffic levels + \item Server response time +\end{itemize} +All of these factors will vary in reality and are independent of the scheme.\\ +The important comparison here is the number of \ac{RT}s as in table \ref{tab:comp-rtt}. +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lc} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Number of RTs} \\\hline + RSA Blind Signatures & 1\\\hline + Clause Blind Schnorr Signatures & 2\\\hline + \end{tabular} + \caption{Comparison of Round-Trips} + \label{tab:comp-rtt} +\end{table} + +While creating \gls{RSABS} have one \ac{RT}, \gls{CSBS} need an additional \ac{RT} for requesting the public $R_0, R_1$. +This means that the time spend for withdrawing is almost \textbf{doubled} (the $ R $ request doesn't have any persistence and therefore requires less time) in comparison to RSA. + +A coin should not be spent immediately after withdrawal or refresh. +Otherwise, an adversary could deanonymize a customer by correlating the timestamps. +The additional \ac{RT} is a drawback of \gls{CSBS} compared to RSA, but negligible due to the fact that a coin must not be spent immediately. + +\section{Security Assumptions} +\label{sec:disc-sec-assumptions} +This section discusses the differences regarding the security assumptions of the schemes. +This section should not explain nor analyze the security assumptions, instead the section focuses on explaining what these assumptions mean and what should be kept in mind about them. +Read section \ref{sec:sign-schemes} and it's references for more information on the assumptions. + +RSA's security assumptions are well known since quite a long time and a lot of research is done. +Despite being a lot of attacks \cite{ganapati:rsactftool} \cite{perez:stoprsa}, RSA is still considered a secure scheme after decades.\\ +For Schnorr Signatures the \acl{DLP} (see \autoref{sec:dlp}) needs to be hard. +Also the \ac{DLP} is well-known and is being researched since decades.\\ +However, with Blind Schorr Signatures an additional assumption needs to hold; the \ac{ROS} problem. +Compared to the other assumptions, \ac{ROS} is relatively new and still a recent research topic. +A recent paper from 2020 on the (in)security of ROS \cite{cryptoeprint:2020:945} broke many schemes relying on ROS being hard, including Schnorr Blind signatures. +The paper on which we rely on (updated in 2021) with the Clause Blind Schnorr Signature Scheme \cite{cryptoeprint:2019:877} is considered secure at the time of writing.\\ + +\section{Risk} +\label{sec:disc-risk} +As introduced in \autoref{sec:disc-sec-assumptions}, \gls{CSBS} rely on an additional assumption currently being researched. +Compared to other schemes, the chosen \gls{CSBS} are very new (published in 2019, updated in 2021). +While every scheme could potentially be broken, older ones already went through a lot of research and their assumptions are well-known. +Therefore, the risk that a vulnerability in \gls{CSBS} will be discovered is probably higher than a newly discovered vulnerability breaking RSA. + +Unpredictability of $ r $ is a key aspect of the signature creation process of \gls{CSBS}. +The redesigned Taler protocols solve this by persisting the nonce and denomination key (described in \autoref{sec:withdraw-protocol-impl}) and checking for reuse of this combination before signature creation. +If this process is malfunctioning (broken implementation, faulty database) or can be circumvented in any way, recovery of a denomination private key is possible. + +An exchange operator can still consider using \gls{CSBS} as denomination scheme, as there are multiple benefits (see \autoref{sec:disc-perf-comp}). +The financial loss in the worst case can be calculated and capped by the validity of a denomination key. +If a vulnerability in the \gls{CSBS} would be detected, an exchange operator could revoke the corresponding denomination keys and change the scheme to \gls{RSABS}. +The wallets can then follow the refund protocol to get the money back. + +\section{Comparison Conclusion} +\label{sec:disc-comp-conclusion} +A detailed comparison of the two blind signature schemes was made. +This last section interprets the results and concludes the comparison. + +\gls{CSBS} on \gls{25519} provide the same security level as \gls{RSABS} with 3072 bit key sizes. +The implementation of \gls{CSBS} is the clear winner in all performance comparisons with RSA 3072 bits. + +1024 bit RSA is faster than the \gls{CSBS} implementation in certain operations. +The \gls{CSBS} implementation still offers better performance for wallets with less CPU power and provides a much higher level of security (comparable to RSA 3072). +As further comparisons show, RSA scales very bad the larger the keys get and \gls{CSBS} performs much better overall. + +As discussed in the risk section \ref{sec:disc-risk}, \gls{CSBS} have an additional security assumption, which is still a recent research topic. +\gls{CSBS} provide various benefits and the risk can be calculated and capped. +An exchange operator who is aware of the discussed risk can use \gls{CSBS} safely. +\gls{CSBS} are best suited for denominations with low value, where many coins are being withdrawn/refreshed. diff --git a/doc/cs/content/6_conclusion.tex b/doc/cs/content/6_conclusion.tex new file mode 100644 index 000000000..c270e765a --- /dev/null +++ b/doc/cs/content/6_conclusion.tex @@ -0,0 +1,70 @@ +\chapter{Conclusion} +This section provides a summary of this work, presents the results and gives an outlook on future work. + +\section{Summary} +In the beginning of the project good knowledge on the current state in research about Blind Schnorr signatures was needed. +Therefore, various papers were read and then the paper "Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model" \cite{cryptoeprint:2019:877} was chosen as basis for the redesign of the Taler protocols.\\ +The next step was to analyze the current Taler protocols and understand the required properties including \textit{\gls{abort-idempotency}}.\\ +With the gathered knowledge (see chapter \ref{chap:preliminaries}) the Taler protocols were redesigned to support \gls{CSBS} (see chapter \ref{chap:design}). +These redesigned protocols were then further specified (chapter \ref{chap:spec}) and then implemented (chapter \ref{chap:implement}). +The implementation includes the main protocols, key management, cryptographic utilities in Taler and the \gls{CSBS} cryptographic routines.\\ +The \gls{CSBS} scheme was analyzed and compared in detail to the RSA Blind Signature scheme (see \ref{chap:disc}). + + +\section{Results} +The thesis provides several results to add support for Schnorr's blind signature in Taler, including: +\begin{itemize} + \item Redesigned Taler protocols to support \gls{CSBS} + \item Implementation of cryptographic routines + \item Implementation of Taler protocols in Exchange + \begin{itemize} + \item Key Management and security module + \item Cryptographic utilities + \item Withdraw protocol + \item Deposit protocol + \end{itemize} + \item Comparison and Analysis + \begin{itemize} + \item Performance (speed, space, latency \& bandwith) + \item Security + \item Scheme Comparison + \end{itemize} + \item Fixing a minor security issue in Taler's current protocols +\end{itemize} +The code is tested, and those tests are integrated in the existing testing framework. +Benchmarks are added for the cryptographic routines and the security module. + +\section{Future Work} +Like in any other project, there is always more that could be done. +This section provides an outlook on what can be done in future work. + +\begin{itemize} + \item Implement wallet + \item Implementing remaining \gls{CSBS} protocols (refresh, tipping protocol, refund etc.) + \item Implementing merchant + \item Security audit of CS implementation + \item Find a solution for withdraw loophole + \item Evaluating \& implementing \gls{CSBS} on other curves +\end{itemize} + +There are some remaining protocols to implement, which were out of scope for this thesis. +To run \gls{CSBS} in production, these protocols have to be implemented too. +Further, the merchant needs to support \gls{CSBS} too. +The merchant implementation can be done fast, as the merchant only verifies denomination signatures in most cases. \\ +Currently, the exchange runs both security modules, the \gls{CSBS} and the RSA security modules. +To reduce unnecessary overhead, this should be changed so that only one security has to be running. +To run \gls{CSBS} in production a security audit from an external company is recommended (as done for other parts in the exchange, see \cite{codeblau:taler-audit}). +A security audit should always be made when implementing big changes like these.\\ +As mentioned in the scope section, the optional goal to find and implement a good solution for the withdraw loophole was dropped. +This was due to the scope shift and because the analysis of the problem showed that finding a good solution needs more research and is a whole project in itself (see \ref{sec:scope} for more information).\\ +Furthermore, \gls{CSBS} could be implemented on other curves. +For example Curve448 \cite{cryptoeprint:2015:625} could be used, as it provides 224 bits of security, wheras \gls{25519} \cite{bern:curve25519} provides about 128 bits of security. +Curve secp256k1 could further improve \gls{CSBS} performance. +While providing support for Curve448 should not be problematic, a potential implementation for secp256k1 needs further analysis (see \cite{bernlange:safecurves} and \cite{bip:schnorr-bitc} for more information). + +\section{Personal Conclusion} +This thesis includes understanding, analyzing, integrating and implementing a recent academic paper \cite{cryptoeprint:2019:877} containing a modern cryptographic scheme. +Furthermore, the implementation is done in Taler, an intuitive and modern solution for a social responsible payment system with high ethical standards. +Although there was a lot of work, we enjoyed working on such a modern and very interesting topic. +Especially the first successful signature verification and the signature scheme performance benchmarks motivated us to push the implementation and integration into Taler forward.\\ +We are happy to provide an implementation of a modern scheme and making it available as free software. \ No newline at end of file diff --git a/doc/cs/content/appendix.tex b/doc/cs/content/appendix.tex new file mode 100644 index 000000000..137a29ba7 --- /dev/null +++ b/doc/cs/content/appendix.tex @@ -0,0 +1,677 @@ +\appendix + +\chapter{Installation} +These installation instructions are meant to run the code developed within this thesis for development- and review-purposes. +For a comprehensive installation instruction follow the Taler documentation +\cite{taler-documentation}. + +\begin{bfhNoteBox} + These instructions are used and tested on Ubuntu 21.10. +\end{bfhNoteBox} + +\section{Dependencies and Setup} +The following dependencies need to be installed for GNUnet and Taler Exchange: +\setupLinuxPrompt{student} +\begin{ubuntu} +sudo apt update +sudo apt install git curl build-essential gcc automake make \ texinfo autoconf uncrustify libtool pkgconf gettext gnutls-bin \ libcurl4-gnutls-dev libgcrypt20-dev libidn2-dev libjansson-dev \ libnss3-dev sqlite pipenv libltdl-dev libsodium-dev libpq-dev \ autopoint libunistring-dev libextractor-dev libpng-dev \ libpulse-dev libsqlite3-dev recutils python3-jinja2 sqlite yapf3 \ postgresql libpq-dev wget libmicrohttpd-dev +export LD\_LIBRARY\_PATH=/usr/local/lib +\end{ubuntu} + +\begin{bfhBox}[BFH-MediumBlue]{Install in a container} +The installation can also be done in a docker or podman container with the ubuntu:21.10 image: +\setupLinuxPrompt{student} +\begin{ubuntu} +podman run -it --name talertest ubuntu:21.10 +\end{ubuntu} +\end{bfhBox} + +\section{Install GNUnet Core} +GNUnet core is both a dependency of the Taler exchange and where we implemented the Clause Blind Schnorr Signature Scheme. +\setupLinuxPrompt{student} +\begin{ubuntu} +git clone https://git.gnunet.org/gnunet.git +cd gnunet +./bootstrap +./configure --enable-benchmarks --prefix=/usr/local +make +make install +make check # Run optionally to verify installation and run tests +\end{ubuntu} + +To run benchmarks run: +\setupLinuxPrompt{student} +\begin{ubuntu} +./src/util/perf_crypto_cs +./src/util/perf_crypto_rsa +\end{ubuntu} + +\section{Install Taler Exchange} +\begin{bfhWarnBox} +Ensure that the current user has privileges in postgresql. +One possible way to do this is:\\ +(where [user] has to be replaced with the name of the system user running the tests) +\setupLinuxPrompt{student} +\begin{ubuntu} +service postgresql start +sudo su +su - postgres +psql +CREATE ROLE [user] LOGIN SUPERUSER; +CREATE DATABASE [user] OWNER [user]; +exit +\end{ubuntu} +\end{bfhWarnBox} + +The Taler exchange can be installed as followed: +\setupLinuxPrompt{student} +\begin{ubuntu} +service postgresql start +createdb talercheck +git clone https://git.taler.net/exchange.git +cd exchange +./bootstrap +./configure --with-gnunet=/usr/local --prefix=/usr/local +./make +./make install +./make check # Run optionally to verify installation and run tests +\end{ubuntu} + +To execute the security module benchmarks run: +\setupLinuxPrompt{student} +\begin{ubuntu} +cd src/util +./test_helper_cs +./test_helper_rsa +\end{ubuntu} + +\chapter{Performance Measurements} +\label{chap:app-perf} + +\section{AMD Ryzen 7 PRO 5850U (Notebook)} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-amd-ryzen-7}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core AMD Ryzen 7 PRO 5850U \\ + Architecture: amd64 \\ + OS: Ubuntu 21.10 Linux 5.13.0-25-generic \#26-Ubuntu SMP Fri Jan 7 15:48:31 UTC 2022 x86\_64 x86\_64 x86\_64 GNU/Linux \\ + libsodium:amd64 version: 1.0.18-1build1 \\ + libgcrypt:amd64 version: 1.8.7-5ubuntu2 +\end{bfhBox} + +\begin{table}[h] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.204 ms \\\hline + RSA 1024 bit & 10x key generation & 126 ms \\\hline + RSA 2048 bit & 10x key generation & 903 ms \\\hline + RSA 3072 bit & 10x key generation & 2684 ms \\\hline + RSA 4096 bit & 10x key generation & 10 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 0.444 ms \\\hline + CS & 10x derivation of blinding secrets & 0.094 ms \\\hline + CS & 10x blinding & 3.332 ms \\\hline + RSA 1024 bit & 10x blinding & 1.282 ms \\\hline + RSA 2048 bit & 10x blinding & 3.012 ms \\\hline + RSA 3072 bit & 10x blinding & 5 ms \\\hline + RSA 4096 bit & 10x blinding & 9 ms \\\hline + \hline + CS & 10x signing & 0.077 ms \\\hline + RSA 1024 bit & 10x signing & 7 ms \\\hline + RSA 2048 bit & 10x signing & 34 ms \\\hline + RSA 3072 bit & 10x signing & 86 ms \\\hline + RSA 4096 bit & 10x signing & 183 ms \\\hline + \hline + CS & 10x unblinding & 0.001 ms \\\hline + RSA 1024 bit & 10x unblinding & 2.991 ms \\\hline + RSA 2048 bit & 10x unblinding & 10 ms \\\hline + RSA 3072 bit & 10x unblinding & 24 ms \\\hline + RSA 4096 bit & 10x unblinding & 44 ms \\\hline + \hline + CS & 10x verifying & 1.358 ms \\\hline + RSA 1024 bit & 10x verifying & 0.876 ms \\\hline + RSA 2048 bit & 10x verifying & 1.836 ms \\\hline + RSA 3072 bit & 10x verifying & 3.075 ms \\\hline + RSA 4096 bit & 10x verifying & 5 ms \\\hline + \end{tabular} + \caption{Comparison on AMD Ryzen 7} + \label{tab:comp-sign-amd-ryzen-7} +\end{table} + +\section{Intel(R) Core(TM) i7-8565U} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-intel-i7}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz \\ + Architecture: amd64 \\ + OS: Ubuntu 21.10 Linux 5.13.0-25-generic \#26-Ubuntu SMP Fri Jan 7 15:48:31 UTC 2022 x86\_64 x86\_64 x86\_64 GNU/Linux \\ + libsodium:amd64 version: 1.0.18-1build1 \\ + libgcrypt:amd64 version: 1.8.7-5ubuntu2 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 1.05 ms \\\hline + RSA 1024 bit & 10x key generation & 189 ms \\\hline + RSA 2048 bit & 10x key generation & 1555 ms \\\hline + RSA 3072 bit & 10x key generation & 5000 ms \\\hline + RSA 4096 bit & 10x key generation & 11 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 2.261 ms \\\hline + CS & 10x derivation of blinding secrets & 0.521 ms \\\hline + CS & 10x blinding & 13 ms \\\hline + RSA 1024 bit & 10x blinding & 2.6 ms \\\hline + RSA 2048 bit & 10x blinding & 4.12 ms \\\hline + RSA 3072 bit & 10x blinding & 7 ms \\\hline + RSA 4096 bit & 10x blinding & 11 ms \\\hline + \hline + CS & 10x signing & 0.405 ms \\\hline + RSA 1024 bit & 10x signing & 9 ms \\\hline + RSA 2048 bit & 10x signing & 44 ms \\\hline + RSA 3072 bit & 10x signing & 108 ms \\\hline + RSA 4096 bit & 10x signing & 216 ms \\\hline + \hline + CS & 10x unblinding & 0.005 ms \\\hline + RSA 1024 bit & 10x unblinding & 3.353 ms \\\hline + RSA 2048 bit & 10x unblinding & 12 ms \\\hline + RSA 3072 bit & 10x unblinding & 27 ms \\\hline + RSA 4096 bit & 10x unblinding & 47 ms \\\hline + \hline + CS & 10x verifying & 4.413 ms \\\hline + RSA 1024 bit & 10x verifying & 1.202 ms \\\hline + RSA 2048 bit & 10x verifying & 2.304 ms \\\hline + RSA 3072 bit & 10x verifying & 4.094 ms \\\hline + RSA 4096 bit & 10x verifying & 6 ms \\\hline + \end{tabular} + \caption{Comparison on Intel(R) Core(TM) i7-8565U} + \label{tab:comp-sign-intel-i7} +\end{table} + +\section{AMD Ryzen Threadripper 1950X 16-Core Processor} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-amd-threadripper}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: AMD Ryzen Threadripper 1950X 16-Core Processor \\ + Architecture: amd64 \\ + OS: Linux 5.13.0-trunk-amd64 \#1 SMP Debian 5.13.12-1~exp1 + (2021-08-20) x86\_64 GNU/Linux \\ + libsodium:amd64 version: 1.9.4-5 \\ + libgcrypt:amd64 version: 1.0.18-1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.442 ms \\\hline + RSA 1024 bit & 10x key generation & 145 ms \\\hline + RSA 2048 bit & 10x key generation & 1167 ms \\\hline + RSA 3072 bit & 10x key generation & 6000 ms \\\hline + RSA 4096 bit & 10x key generation & 11 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 1.043 ms \\\hline + CS & 10x derivation of blinding secrets & 0.242 ms \\\hline + CS & 10x blinding & 7 ms \\\hline + RSA 1024 bit & 10x blinding & 2.258 ms \\\hline + RSA 2048 bit & 10x blinding & 4.744 ms \\\hline + RSA 3072 bit & 10x blinding & 9 ms \\\hline + RSA 4096 bit & 10x blinding & 14 ms \\\hline + \hline + CS & 10x signing & 0.270 ms \\\hline + RSA 1024 bit & 10x signing & 10 ms \\\hline + RSA 2048 bit & 10x signing & 47 ms \\\hline + RSA 3072 bit & 10x signing & 119 ms \\\hline + RSA 4096 bit & 10x signing & 248 ms \\\hline + \hline + CS & 10x unblinding & 0.003 ms \\\hline + RSA 1024 bit & 10x unblinding & 4.086 ms \\\hline + RSA 2048 bit & 10x unblinding & 14 ms \\\hline + RSA 3072 bit & 10x unblinding & 34 ms \\\hline + RSA 4096 bit & 10x unblinding & 60 ms \\\hline + \hline + CS & 10x verifying & 2.392 ms \\\hline + RSA 1024 bit & 10x verifying & 1.137 ms \\\hline + RSA 2048 bit & 10x verifying & 2.797 ms \\\hline + RSA 3072 bit & 10x verifying & 5 ms \\\hline + RSA 4096 bit & 10x verifying & 7 ms \\\hline + \end{tabular} + \caption{Comparison on AMD Ryzen Threadripper 1950X} + \label{tab:comp-sign-amd-threadripper} +\end{table} + +\section{Intel(R) Xeon(R) CPU E5-2630} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-intel-xeon}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: Intel(R) Xeon(R) CPU E5-2630 0 @ 2.30GHz \\ + Architecture: amd64 \\ + OS: Linux 5.10.0-8-amd64 \#1 SMP Debian 5.10.46-4 (2021-08-03) x86\_64\\ + libsodium:amd64 version: 1.0.18-1\\ + libgcrypt:amd64 version: 1.8.7-6 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.606 ms \\\hline + RSA 1024 bit & 10x key generation & 329 ms \\\hline + RSA 2048 bit & 10x key generation & 3210 ms \\\hline + RSA 3072 bit & 10x key generation & 12 000 ms \\\hline + RSA 4096 bit & 10x key generation & 40 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 1.527 ms \\\hline + CS & 10x derivation of blinding secrets & 0.329 ms \\\hline + CS & 10x blinding & 9 ms \\\hline + RSA 1024 bit & 10x blinding & 4.026 ms \\\hline + RSA 2048 bit & 10x blinding & 9 ms \\\hline + RSA 3072 bit & 10x blinding & 18 ms \\\hline + RSA 4096 bit & 10x blinding & 27 ms \\\hline + \hline + CS & 10x signing & 0.274 ms \\\hline + RSA 1024 bit & 10x signing & 21 ms \\\hline + RSA 2048 bit & 10x signing & 96 ms \\\hline + RSA 3072 bit & 10x signing & 237 ms \\\hline + RSA 4096 bit & 10x signing & 482 ms \\\hline + \hline + CS & 10x unblinding & 0.004 ms \\\hline + RSA 1024 bit & 10x unblinding & 7 ms \\\hline + RSA 2048 bit & 10x unblinding & 25 ms \\\hline + RSA 3072 bit & 10x unblinding & 58 ms \\\hline + RSA 4096 bit & 10x unblinding & 99 ms \\\hline + \hline + CS & 10x verifying & 4.334 ms \\\hline + RSA 1024 bit & 10x verifying & 2.190 ms \\\hline + RSA 2048 bit & 10x verifying & 5 ms \\\hline + RSA 3072 bit & 10x verifying & 11 ms \\\hline + RSA 4096 bit & 10x verifying & 14 ms \\\hline + \end{tabular} + \caption{Comparison on Intel(R) Xeon(R) CPU E5-2630} + \label{tab:comp-sign-intel-xeon} +\end{table} + +\section{Intel(R) Pentium(R) 3558U} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-intel-pentium}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: Intel(R) Pentium(R) 3558U @ 1.70GHz \\ + Architecture: amd64 \\ + OS: Linux 5.10.0-8-amd64 \#1 SMP Debian 5.10.46-3 (2021-07-28) x86\_64\\ + libsodium:amd64 version: 1.0.18-1\\ + libgcrypt:amd64 version: 1.8.7-6 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.53 ms \\\hline + RSA 1024 bit & 10x key generation & 524 ms \\\hline + RSA 2048 bit & 10x key generation & 3357 ms \\\hline + RSA 3072 bit & 10x key generation & 15 000 ms \\\hline + RSA 4096 bit & 10x key generation & 37 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 1.375 ms \\\hline + CS & 10x derivation of blinding secrets & 0.349 ms \\\hline + CS & 10x blinding & 8 ms \\\hline + RSA 1024 bit & 10x blinding & 4.86 ms \\\hline + RSA 2048 bit & 10x blinding & 11 ms \\\hline + RSA 3072 bit & 10x blinding & 19 ms \\\hline + RSA 4096 bit & 10x blinding & 31 ms \\\hline + \hline + CS & 10x signing & 0.283 ms \\\hline + RSA 1024 bit & 10x signing & 26 ms \\\hline + RSA 2048 bit & 10x signing & 117 ms \\\hline + RSA 3072 bit & 10x signing & 292 ms \\\hline + RSA 4096 bit & 10x signing & 571 ms \\\hline + \hline + CS & 10x unblinding & 0.003 ms \\\hline + RSA 1024 bit & 10x unblinding & 8 ms \\\hline + RSA 2048 bit & 10x unblinding & 30 ms \\\hline + RSA 3072 bit & 10x unblinding & 67 ms \\\hline + RSA 4096 bit & 10x unblinding & 111 ms \\\hline + \hline + CS & 10x verifying & 3.769 ms \\\hline + RSA 1024 bit & 10x verifying & 2.616 ms \\\hline + RSA 2048 bit & 10x verifying & 6 ms \\\hline + RSA 3072 bit & 10x verifying & 11 ms \\\hline + RSA 4096 bit & 10x verifying & 17 ms \\\hline + \end{tabular} + \caption{Comparison on Intel(R) Pentium(R) 3558U} + \label{tab:comp-sign-intel-pentium} +\end{table} + + +\section{arm64} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-arm64}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core arm64\\ + Architecture: ARM64 \\ + OS: Linux ten64 5.11.0-31-generic \#33+testsfp1 SMP Mon Aug 23 16:07:41 UTC 2021 aarch64 aarch64 aarch64 GNU/Linux \\ + libsodium:arm64 version: 1.8.7-2ubuntu2.1 \\ + libgcrypt:arm64 version: 1.0.18-1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 2.896 ms \\\hline + RSA 1024 bit & 10x key generation & 839 ms \\\hline + RSA 2048 bit & 10x key generation & 8000 ms \\\hline + RSA 3072 bit & 10x key generation & 17 000 ms \\\hline + RSA 4096 bit & 10x key generation & 82 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 6 ms \\\hline + CS & 10x derivation of blinding secrets & 0.713 ms \\\hline + CS & 10x blinding & 23 ms \\\hline + RSA 1024 bit & 10x blinding & 11 ms \\\hline + RSA 2048 bit & 10x blinding & 28 ms \\\hline + RSA 3072 bit & 10x blinding & 51 ms \\\hline + RSA 4096 bit & 10x blinding & 81 ms \\\hline + \hline + CS & 10x signing & 0.321 ms \\\hline + RSA 1024 bit & 10x signing & 57 ms \\\hline + RSA 2048 bit & 10x signing & 263 ms \\\hline + RSA 3072 bit & 10x signing & 685 ms \\\hline + RSA 4096 bit & 10x signing & 1385 ms \\\hline + \hline + CS & 10x unblinding & 0.006 ms \\\hline + RSA 1024 bit & 10x unblinding & 23 ms \\\hline + RSA 2048 bit & 10x unblinding & 79 ms \\\hline + RSA 3072 bit & 10x unblinding & 171 ms \\\hline + RSA 4096 bit & 10x unblinding & 296 ms \\\hline + \hline + CS & 10x verifying & 11ms \\\hline + RSA 1024 bit & 10x verifying & 5 ms \\\hline + RSA 2048 bit & 10x verifying & 15 ms \\\hline + RSA 3072 bit & 10x verifying & 27 ms \\\hline + RSA 4096 bit & 10x verifying & 45 ms \\\hline + \end{tabular} + \caption{Comparison on arm64} + \label{tab:comp-sign-arm64} +\end{table} + +\section{AMD Ryzen Embedded R1606G} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-amd-embedded}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 4-core AMD Ryzen Embedded R1606G with Radeon Vega Gfx\\ + Architecture: amd64 \\ + OS: Linux computer 5.13.0-25-generic \#26-Ubuntu SMP Fri Jan 7 15:48:31 UTC 2022 x86\_64 x86\_64 x86\_64 GNU/Linux\\ + libsodium:amd64 version: 1.8.7-5ubuntu2 \\ + libgcrypt:amd64 version: 1.0.18-1build1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 2.373 ms \\\hline + RSA 1024 bit & 10x key generation & 184 ms \\\hline + RSA 2048 bit & 10x key generation & 2132 ms \\\hline + RSA 3072 bit & 10x key generation & 8000 ms \\\hline + RSA 4096 bit & 10x key generation & 21 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 1.09 ms \\\hline + CS & 10x derivation of blinding secrets & 0.43 ms \\\hline + CS & 10x blinding & 6 ms \\\hline + RSA 1024 bit & 10x blinding & 3.886 ms \\\hline + RSA 2048 bit & 10x blinding & 7 ms \\\hline + RSA 3072 bit & 10x blinding & 14 ms \\\hline + RSA 4096 bit & 10x blinding & 23 ms \\\hline + \hline + CS & 10x signing & 0.379 ms \\\hline + RSA 1024 bit & 10x signing & 15 ms \\\hline + RSA 2048 bit & 10x signing & 71 ms \\\hline + RSA 3072 bit & 10x signing & 177 ms \\\hline + RSA 4096 bit & 10x signing & 357 ms \\\hline + \hline + CS & 10x unblinding & 0.001 ms \\\hline + RSA 1024 bit & 10x unblinding & 6 ms \\\hline + RSA 2048 bit & 10x unblinding & 24 ms \\\hline + RSA 3072 bit & 10x unblinding & 53 ms \\\hline + RSA 4096 bit & 10x unblinding & 93 ms \\\hline + \hline + CS & 10x verifying & 2.610 ms \\\hline + RSA 1024 bit & 10x verifying & 2.303 ms \\\hline + RSA 2048 bit & 10x verifying & 4.386 ms \\\hline + RSA 3072 bit & 10x verifying & 7 ms \\\hline + RSA 4096 bit & 10x verifying & 11 ms \\\hline + \end{tabular} + \caption{Comparison on AMD Ryzen Embedded R1606G} + \label{tab:comp-sign-amd-embedded} +\end{table} + +\section{risc64} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-risc64}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 4-core risc64 processor\\ + OS: Linux risc-v-unleashed-000 5.11.0-1022-generic \#23~20.04.1-Ubuntu SMP Thu Oct 21 10:16:27 UTC 2021 riscv64 riscv64 riscv64 GNU/Linux\\ + libsodium:riscv64 version: 1.8.7-5ubuntu2 \\ + libgcrypt:riscv64 version: 1.0.18-1build1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 4.144 ms \\\hline + RSA 1024 bit & 10x key generation & 2923 ms \\\hline + RSA 2048 bit & 10x key generation & 28 000 ms \\\hline + RSA 3072 bit & 10x key generation & 174 000 ms \\\hline + RSA 4096 bit & 10x key generation & 600 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 10 ms \\\hline + CS & 10x derivation of blinding secrets & 2.514 ms \\\hline + CS & 10x blinding & 72 ms \\\hline + RSA 1024 bit & 10x blinding & 37 ms \\\hline + RSA 2048 bit & 10x blinding & 93 ms \\\hline + RSA 3072 bit & 10x blinding & 170 ms \\\hline + RSA 4096 bit & 10x blinding & 277 ms \\\hline + \hline + CS & 10x signing & 1.697 ms \\\hline + RSA 1024 bit & 10x signing & 215 ms \\\hline + RSA 2048 bit & 10x signing & 1040 ms \\\hline + RSA 3072 bit & 10x signing & 2883 ms \\\hline + RSA 4096 bit & 10x signing & 5000 ms \\\hline + \hline + CS & 10x unblinding & 0.022 ms \\\hline + RSA 1024 bit & 10x unblinding & 62 ms \\\hline + RSA 2048 bit & 10x unblinding & 150 ms \\\hline + RSA 3072 bit & 10x unblinding & 275 ms \\\hline + RSA 4096 bit & 10x unblinding & 431 ms \\\hline + \hline + CS & 10x verifying & 29 ms \\\hline + RSA 1024 bit & 10x verifying & 22 ms \\\hline + RSA 2048 bit & 10x verifying & 54 ms \\\hline + RSA 3072 bit & 10x verifying & 99 ms \\\hline + RSA 4096 bit & 10x verifying & 166 ms \\\hline + \end{tabular} + \caption{Comparison on risc64} + \label{tab:comp-sign-risc64} +\end{table} + +\section{POWER9} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-POWER9}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 176-core power9\\ + architecture: pp64le \\ + OS: Linux power9 5.11.0-34-generic \#36-Ubuntu SMP Thu Aug 26 19:19:54 UTC 2021 ppc64le ppc64le ppc64le GNU/Linux \\ + libsodium:a::ppc64el version: 1.8.7-2ubuntu2.1 \\ + libgcrypt::ppc64el version: 1.0.18-1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 0.275 ms \\\hline + RSA 1024 bit & 10x key generation & 290 ms \\\hline + RSA 2048 bit & 10x key generation & 3743 ms \\\hline + RSA 3072 bit & 10x key generation & 15 000 ms \\\hline + RSA 4096 bit & 10x key generation & 45 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 0.749 ms \\\hline + CS & 10x derivation of blinding secrets & 0.267 ms \\\hline + CS & 10x blinding & 4.996 ms \\\hline + RSA 1024 bit & 10x blinding & 3.952 ms \\\hline + RSA 2048 bit & 10x blinding & 10 ms \\\hline + RSA 3072 bit & 10x blinding & 17 ms \\\hline + RSA 4096 bit & 10x blinding & 27 ms \\\hline + \hline + CS & 10x signing & 0.221 ms \\\hline + RSA 1024 bit & 10x signing & 25 ms \\\hline + RSA 2048 bit & 10x signing & 135 ms \\\hline + RSA 3072 bit & 10x signing & 381 ms \\\hline + RSA 4096 bit & 10x signing & 762 ms \\\hline + \hline + CS & 10x unblinding & 0.002 ms \\\hline + RSA 1024 bit & 10x unblinding & 9 ms \\\hline + RSA 2048 bit & 10x unblinding & 34 ms \\\hline + RSA 3072 bit & 10x unblinding & 80 ms \\\hline + RSA 4096 bit & 10x unblinding & 141 ms \\\hline + \hline + CS & 10x verifying & 2.458 ms \\\hline + RSA 1024 bit & 10x verifying & 2.365 ms \\\hline + RSA 2048 bit & 10x verifying & 6 ms \\\hline + RSA 3072 bit & 10x verifying & 10 ms \\\hline + RSA 4096 bit & 10x verifying & 16 ms \\\hline + \end{tabular} + \caption{Comparison on POWER9} + \label{tab:comp-sign-POWER9} +\end{table} + +\section{ARMv7 Processor} +Detailed comparison of each operation can be found in table \ref{tab:comp-sign-armv7}. +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core ARMv7 Processor rev 3 (v7l) + Architecture: armv7 \\ + OS: Linux odroidxu4 4.14.150-odroidxu4 \#2 SMP PREEMPT Mon Oct 28 08:07:45 CET 2019 armv7l GNU/Linux\\ + libsodium:armhf version: 1.9.4-5 \\ + libgcrypt:armhf version: 1.0.18-1 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{llr} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Operation} & \textbf{Speed} \\\hline + CS & 10x key generation & 1.719 ms \\\hline + RSA 1024 bit & 10x key generation & 1050 ms \\\hline + RSA 2048 bit & 10x key generation & 8000 ms \\\hline + RSA 3072 bit & 10x key generation & 53 000 ms \\\hline + RSA 4096 bit & 10x key generation & 159 000 ms \\\hline + \hline + CS & 10x r0, r1 derive and R1,R2 calculation & 3.621 ms \\\hline + CS & 10x derivation of blinding secrets & 0.514 ms \\\hline + CS & 10x blinding & 24 ms \\\hline + RSA 1024 bit & 10x blinding & 10 ms \\\hline + RSA 2048 bit & 10x blinding & 26 ms \\\hline + RSA 3072 bit & 10x blinding & 45 ms \\\hline + RSA 4096 bit & 10x blinding & 78 ms \\\hline + \hline + CS & 10x signing & 0.481 ms \\\hline + RSA 1024 bit & 10x signing & 87 ms \\\hline + RSA 2048 bit & 10x signing & 385 ms \\\hline + RSA 3072 bit & 10x signing & 1038 ms \\\hline + RSA 4096 bit & 10x signing & 2073 ms \\\hline + \hline + CS & 10x unblinding & 0.008 ms \\\hline + RSA 1024 bit & 10x unblinding & 26 ms \\\hline + RSA 2048 bit & 10x unblinding & 90 ms \\\hline + RSA 3072 bit & 10x unblinding & 195 ms \\\hline + RSA 4096 bit & 10x unblinding & 344 ms \\\hline + \hline + CS & 10x verifying & 11 ms \\\hline + RSA 1024 bit & 10x verifying & 5 ms \\\hline + RSA 2048 bit & 10x verifying & 15 ms \\\hline + RSA 3072 bit & 10x verifying & 28 ms \\\hline + RSA 4096 bit & 10x verifying & 42 ms \\\hline + \end{tabular} + \caption{Comparison on ARMv7} + \label{tab:comp-sign-armv7} +\end{table} + + +\section{Performance of the Security Module} +These performance measurements are only done on one hardware setup. +The performance tests of the cryptographic routines are more meaningful, the architecture of the Taler exchange could change a lot. +Furthermore, there could be made performance improvements at costs of security by doing the operations requiring the private keys directly in the httpd process. +Because of security reasons, the current design with the security module makes a lot of sense. +It has to be kept in mind that the following performance benchmarks are interesting to see, but could vary a lot with changes inside the codebase. +The performance of the signatures with the security module can be found in table \ref{tab:comp-sign-full} +\begin{bfhBox}[BFH-MediumBlue]{Setup} + CPU: 8-core AMD Ryzen 7 PRO 5850U \\ + OS: Ubuntu 21.10 Linux 5.13.0-25-generic \#26-Ubuntu SMP Fri Jan 7 15:48:31 UTC 2022 x86\_64 x86\_64 x86\_64 GNU/Linux \\ + libsodium version: 1.0.18-1build1 \\ + libgcrypt version: 1.8.7-5ubuntu2 +\end{bfhBox} + +\begin{table}[ht] + \centering + \colorlet{BFH-table}{BFH-MediumBlue!10} + \colorlet{BFH-tablehead}{BFH-MediumBlue!50} + \setupBfhTabular + \begin{tabular}{lll} + \rowcolor{BFH-tablehead} + \textbf{Signature Scheme} & \textbf{Test} & \textbf{Speed} \\\hline + CS & 100 sequential signature operations & 2.591 ms \\\hline + RSA 1024 bit & 100 sequential signature operations & 79 ms \\\hline + RSA 2048 bit & 100 sequential signature operations & 350 ms \\\hline + RSA 3072 bit & 100 sequential signature operations & 893 ms \\\hline + RSA 4092 & 100 sequential signature operations & 1811 ms \\\hline + \hline + CS & 100 parallel signature operations & 14 ms \\\hline + RSA 1024 bit & 100 parallel signature operations & 125 ms \\\hline + RSA 2048 bit & 100 parallel signature operations & 573ms \\\hline + RSA 3072 bit & 100 parallel signature operations & 1420 ms \\\hline + RSA 4092 & 100 parallel signature operations & 3279 ms \\\hline + \hline + CS & 800 parallel signature operations & 19 ms \\\hline + RSA 1024 bit & 800 parallel signature operations & 137 ms \\\hline + RSA 2048 bit & 800 parallel signature operations & 653 ms \\\hline + RSA 3072 bit & 800 parallel signature operations & 1451 ms \\\hline + RSA 4092 & 800 parallel signature operations & 3388 ms \\\hline + \end{tabular} + \caption{Performance comparison of the security module} + \label{tab:comp-sign-full} +\end{table} + +\input{content/appendix/rsa-redesign.tex} diff --git a/doc/cs/content/appendix/crypto_implementation.tex b/doc/cs/content/appendix/crypto_implementation.tex new file mode 100644 index 000000000..9ae9b5865 --- /dev/null +++ b/doc/cs/content/appendix/crypto_implementation.tex @@ -0,0 +1,279 @@ +\begin{lstlisting}[style=bfh-c,language=C,, caption={Crypto Implementation API}, label={lst:cryptoapi}] + #include + + /** + * IMPLEMENTATION NOTICE: + * + * This is an implementation of the Schnorr, Blind Schnorr and + * Clause Blind Schnorr Signature Scheme using Curve25519. + * We use libsodium wherever possible. + * + * Blind Schnorr: The Blind Schnorr Signature Scheme is BROKEN! + * Use the Clause Blind Schnorr Signature Scheme instead. + * + * Clause Blind Schnorr Signature Scheme: + * This is a variation of the Blind Schnorr Signature Scheme where all operations + * before the signature creation are performed twice. + * The signer randomly chooses one of the two sessions and only creates the signature for this session. + * Note that the Clause part needs to be implemented by whoever uses this API. + * Further details about the Clause Blind Schnorr Signature Scheme can be found here: + * https://eprint.iacr.org/2019/877.pdf + */ + + + /** + * Curve25519 Scalar + */ + struct GNUNET_CRYPTO_Cs25519Scalar + { + /** + * 32 byte scalar + */ + unsigned char d[crypto_core_ed25519_SCALARBYTES]; + }; + + + /** + * Curve25519 point + */ + struct GNUNET_CRYPTO_Cs25519Point + { + /** + * This is a point on the Curve25519. + * The x coordinate can be restored using the y coordinate + */ + unsigned char y[crypto_core_ed25519_BYTES]; + }; + + + /** + * The private information of an Schnorr key pair. + */ + struct GNUNET_CRYPTO_CsPrivateKey + { + struct GNUNET_CRYPTO_Cs25519Scalar scalar; + }; + + + /** + * The public information of an Schnorr key pair. + */ + struct GNUNET_CRYPTO_CsPublicKey + { + struct GNUNET_CRYPTO_Cs25519Point point; + }; + + + /** + * Secret used for blinding (alpha and beta). + */ + struct GNUNET_CRYPTO_CsBlindingSecret + { + struct GNUNET_CRYPTO_Cs25519Scalar alpha; + struct GNUNET_CRYPTO_Cs25519Scalar beta; + }; + + + /** + * the private r used in the signature + */ + struct GNUNET_CRYPTO_CsRSecret + { + struct GNUNET_CRYPTO_Cs25519Scalar scalar; + }; + + + /** + * the public R (derived from r) used in c + */ + struct GNUNET_CRYPTO_CsRPublic + { + struct GNUNET_CRYPTO_Cs25519Point point; + }; + + /** + * Schnorr c to be signed + */ + struct GNUNET_CRYPTO_CsC + { + struct GNUNET_CRYPTO_Cs25519Scalar scalar; + }; + + /** + * s in the signature + */ + struct GNUNET_CRYPTO_CsS + { + struct GNUNET_CRYPTO_Cs25519Scalar scalar; + }; + + /** + * blinded s in the signature + */ + struct GNUNET_CRYPTO_CsBlindS + { + struct GNUNET_CRYPTO_Cs25519Scalar scalar; + }; + + /** + * CS Signtature containing scalar s and point R + */ + struct GNUNET_CRYPTO_CsSignature + { + /** + * Schnorr signatures are composed of a scalar s and a curve point + */ + struct GNUNET_CRYPTO_CsS s_scalar; + struct GNUNET_CRYPTO_Cs25519Point r_point; + }; + + /** + * Nonce + */ + struct GNUNET_CRYPTO_CsNonce + { + /*a nonce*/ + unsigned char nonce[256 / 8]; + }; + + + /** + * Create a new random private key. + * + * @param[out] priv where to write the fresh private key + */ + void + GNUNET_CRYPTO_cs_private_key_generate (struct GNUNET_CRYPTO_CsPrivateKey *priv); + + + /** + * Extract the public key of the given private key. + * + * @param priv the private key + * @param[out] pub where to write the public key + */ + void + GNUNET_CRYPTO_cs_private_key_get_public (const struct GNUNET_CRYPTO_CsPrivateKey *priv, + struct GNUNET_CRYPTO_CsPublicKey *pub); + + + /** + * Derive a new secret r pair r0 and r1. + * In original papers r is generated randomly + * To provide abort-idempotency, r needs to be derived but still needs to be UNPREDICTABLE + * To ensure unpredictability a new nonce should be used when a new r needs to be derived. + * Uses HKDF internally. + * Comment: Can be done in one HKDF shot and split output. + * + * @param nonce is a random nonce + * @param lts is a long-term-secret in form of a private key + * @param[out] r array containing derived secrets r0 and r1 + */ + void + GNUNET_CRYPTO_cs_r_derive (const struct GNUNET_CRYPTO_CsNonce *nonce, + const struct GNUNET_CRYPTO_CsPrivateKey *lts, + struct GNUNET_CRYPTO_CsRSecret r[2]); + + + /** + * Extract the public R of the given secret r. + * + * @param r_priv the private key + * @param[out] r_pub where to write the public key + */ + void + GNUNET_CRYPTO_cs_r_get_public (const struct GNUNET_CRYPTO_CsRSecret *r_priv, + struct GNUNET_CRYPTO_CsRPublic *r_pub); + + + /** + * Derives new random blinding factors. + * In original papers blinding factors are generated randomly + * To provide abort-idempotency, blinding factors need to be derived but still need to be UNPREDICTABLE + * To ensure unpredictability a new nonce has to be used. + * Uses HKDF internally + * + * @param secret is secret to derive blinding factors + * @param secret_len secret length + * @param[out] bs array containing the two derivedGNUNET_CRYPTO_CsBlindingSecret + */ + void + GNUNET_CRYPTO_cs_blinding_secrets_derive (const struct GNUNET_CRYPTO_CsNonce *blind_seed, + struct GNUNET_CRYPTO_CsBlindingSecret bs[2]); + + + /** + * Calculate two blinded c's + * Comment: One would be insecure due to Wagner's algorithm solving ROS + * + * @param bs array of the two blinding factor structs each containing alpha and beta + * @param r_pub array of the two signer's nonce R + * @param pub the public key of the signer + * @param msg the message to blind in preparation for signing + * @param msg_len length of message msg + * @param[out] blinded_c array of the two blinded c's + */ + void + GNUNET_CRYPTO_cs_calc_blinded_c (const struct GNUNET_CRYPTO_CsBlindingSecret bs[2], + const struct GNUNET_CRYPTO_CsRPublic r_pub[2], + const struct GNUNET_CRYPTO_CsPublicKey *pub, + const void *msg, + size_t msg_len, + struct GNUNET_CRYPTO_CsC blinded_c[2]); + + + /** + * Sign a blinded c + * This function derives b from a nonce and a longterm secret + * In original papers b is generated randomly + * To provide abort-idempotency, b needs to be derived but still need to be UNPREDICTABLE. + * To ensure unpredictability a new nonce has to be used for every signature + * HKDF is used internally for derivation + * r0 and r1 can be derived prior by using GNUNET_CRYPTO_cs_r_derive + * + * @param priv private key to use for the signing and as LTS in HKDF + * @param r array of the two secret nonce from the signer + * @param c array of the two blinded c to sign c_b + * @param nonce is a random nonce + * @param[out] blinded_signature_scalar where to write the signature + * @return 0 or 1 for b (see Clause Blind Signature Scheme) + */ + int + GNUNET_CRYPTO_cs_sign_derive(const struct GNUNET_CRYPTO_CsPrivateKey *priv, + const struct GNUNET_CRYPTO_CsRSecret r[2], + const struct GNUNET_CRYPTO_CsC c[2], + const struct GNUNET_CRYPTO_CsNonce *nonce, + struct GNUNET_CRYPTO_CsBlindS *blinded_signature_scalar + ); + + + /** + * Unblind a blind-signed signature using a c that was blinded + * + * @param blinded_signature_scalar the signature made on the blinded c + * @param bs the blinding factors used in the blinding + * @param[out] signature_scalar where to write the unblinded signature + */ + void + GNUNET_CRYPTO_cs_unblind (const struct GNUNET_CRYPTO_CsBlindS *blinded_signature_scalar, + const struct GNUNET_CRYPTO_CsBlindingSecret *bs, + struct GNUNET_CRYPTO_CsS *signature_scalar); + + + /** + * Verify whether the given message corresponds to the given signature and the + * signature is valid with respect to the given public key. + * + * @param sig signature that is being validated + * @param pub public key of the signer + * @param msg is the message that should be signed by @a sig (message is used to calculate c) + * @param msg_len is the message length + * @returns #GNUNET_YES on success, #GNUNET_SYSERR if key parameter(s) invalid #GNUNET_NO if signature invalid + */ + enum GNUNET_GenericReturnValue + GNUNET_CRYPTO_cs_verify (const struct GNUNET_CRYPTO_CsSignature *sig, + const struct GNUNET_CRYPTO_CsPublicKey *pub, + const void *msg, + size_t msg_len); + +\end{lstlisting} \ No newline at end of file diff --git a/doc/cs/content/appendix/rsa-redesign.tex b/doc/cs/content/appendix/rsa-redesign.tex new file mode 100644 index 000000000..463b9735f --- /dev/null +++ b/doc/cs/content/appendix/rsa-redesign.tex @@ -0,0 +1,209 @@ +\chapter{Redesigned RSA Protocols} +In order to bring the RSA and \gls{CSBS} protocols closer, this chapter describes a variant of the RSA protocols with the same changes as in the \gls{CSBS} versions (where they can be applied). + + +\section{Withdraw Protocol} +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p & & \text{reserve public key } W_p + \\ \text{denomination public key } D_p = e, N & & \text{denomination keys } d_s, D_p + \\ & & + \\\text{generate withdraw secret:} + \\ \omega := randombytes(32) + \\ \text{persist } \langle \omega, D_p \rangle + \\\text{derive coin key pair:} & & + \\ c_s := \text{HKDF}(256, \omega, \text{"cs"}) + \\ C_p := \text{Ed25519.GetPub}(c_s) + \\ \text{blind:} & & + \\ b_s := \text{HKDF}(256, \omega, \text{"b-seed"}) + \\ r := \text{FDH}(b_s) + \\ m' := \text{FDH}(N, C_p)*r^{e} \mod N & & + \\ \text{sign with reserve private key:} & & + \\ \rho_W := \langle D_p, m' \rangle & & + \\ \sigma_W := \text{Ed25519.Sign}(w_s, \rho_W) & & + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho = W_p, \sigma_W, \rho_W} & + \\ & & \langle D_p, m' \rangle := \rho_W + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & \text{check } \text{Ed25519.Verify}(W_p, \rho_W, \sigma_W) + \\ & & \sigma'_c = (m')^{d_s} \mod N + \\ & & \text{decrease balance if sufficient and} + \\ & & \text{persist } \langle D_p, s \rangle + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\sigma'_c} & + \\ \text{unblind:}& & + \\ \sigma_c = \sigma'_c*r^{-1} & & + \\ \text{verify signature:}& & + \\ \textbf{check if } \sigma_c^{e} = \text{FDH}(N, C_p) & & + \\ & & + \\ \text{resulting coin: } c_s, C_p, \sigma_c, D_p & & + \\ & & + \\ \text{implementation note: minimum of} + \\ \text{persisted values is } \langle \omega, \sigma_c \rangle + \end{array}$ + } + \end{equation*} + \caption{Redesigned RSA withdrawal process} + \label{fig:withdrawal-process-rsa-redesign} +\end{figure} + +The changes to the RSA witdhdraw protocol (see \autoref{fig:withdrawal-process-rsa-redesign}) are limited to the derivation of the coin and blinding factor. + + +\section{Refresh Protocol} +The changes to the refresh protocol are related to the derivation of transfer secrets and subsequent operations, see \autoref{fig:refresh-derive-rsa-redesign}, \autoref{fig:refresh-part1-rsa-redesign} and \autoref{fig:refresh-part2-rsa-redesign}. +\begin{figure}[htp] + \centering + \fbox{% + \procedure[codesize=\small]{$\text{RefreshDerive}(t, \langle e, N \rangle, C_p)$}{% + T := \text{Curve25519.GetPub}(t) \\ + x := \textrm{ECDH-EC}(t, C_p) \\ + b_s := \text{HKDF}(256, x, \text{"b-seed"}) \\ + r := \text{FDH}(b_s) \\ + c'_s := \text{HKDF}(256,x,"c") \\ + C'_p := \text{Ed25519.GetPub}(c'_s) \\ + \overline{m} := r^e * C'_p \mod N \\ + \pcreturn \langle T, c_s', C_p', \overline{m} \rangle + } + } + \caption{Redesigned RSA RefreshDerive algorithm} + \label{fig:refresh-derive-rsa-redesign} +\end{figure} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{denomination public key } D_{p(i)} & & \text{denomination keys } d_{s(i)}, D_{p(i)} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_c^{(0)} \rangle & & + % refresh request + \\ \text{Select} \langle N_t, e_t\rangle := D_{p(t)} \in D_{p(i)} + \\ \omega := randombytes(32) + \\ \text{persist } \langle \omega, D_{p(t)} \rangle + \\ \textbf{for } i = 1, \dots, \kappa: % generate k derives + \\ t_i := \text{HKDF}(256, \omega,\text{"t} i \text{"} ) % seed generation + \\ X_i := \text{RefreshDerive}(t_i, D_{p(t)}, C_p^{(0)}) + \\ (T_i, c_s^{(i)}, C_p^{(i)}, \overline{m}_i) := X_i + \\ \textbf{endfor} + \\ h_T := H(T_1, \dots, T_k) + \\ h_{\overline{m}} := H(\overline{m}_1, \dots, \overline{m}_k) + \\ h_C := H(h_t, h_{\overline{m}}) + \\ \rho_{RC} := \langle h_C, D_{p(t)}, D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} \rangle + \\ \sigma_{RC} := \text{Ed25519.Sign}(c_s^{(0)}, \rho_{RC}) + \\ \text{Persist refresh-request} \langle \omega, \rho_{RC}, \sigma_{RC} \rangle + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RC}, \sigma_{RC}} & + % Exchange checks refresh request + \\ & & (h_C, D_{p(t)}, D_{p(0)}, C_p^{(0)}, \sigma_C^{(0)} = \rho_{RC}) + \\ & & \textbf{check} \text{Ed25519.Verify}(C_p^{(0)}, \sigma_{RC}, \rho_{RC}) + \\ & & x \rightarrow \text{GetOldRefresh}(\rho_{RC}) + \\ & & \textbf{Comment: }\text{GetOldRefresh} (\rho_{RC} \mapsto \{\bot,\gamma\}) + \\ & & \pcif x = \bot + \\ & & v := \text{Denomination}(D_{p(t)}) + \\ & & \langle e_0, N_0 \rangle := D_{p(0)} + \\ & & \textbf{check } \text{IsOverspending}(C_p^{(0)}, D_ {p(0)}, v) + \\ & & \textbf{check } D_{p(t)} \in \{D_{p(i)}\} + \\ & & \textbf{check } \text{FDH}(N_0, C_p^{(0)}) \equiv_{N_0} (\sigma_0^{(0)})^{e_0} + \\ & & \text{MarkFractionalSpend}(C_p^{(0)}, v) + \\ & & \gamma \leftarrow \{1, \dots, \kappa\} + \\ & & \text{Persist refresh-record } \langle \rho_{RC},\gamma \rangle + \\ & & \pcelse + \\ & & \gamma := x + \\ & & \textbf{endif} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\gamma} & + \\ + \\ + \\ & \textit{Continued in figure \ref{fig:refresh-part2}} & + %\\ \pcintertext[dotted]{(Continued in Figure)} + \end{array}$ + } + \end{equation*} + \caption{Redesigned RSA refresh protocol (commit phase)} + \label{fig:refresh-part1-rsa-redesign} +\end{figure} + +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ & \textit{Continuation of figure \ref{fig:refresh-part1}} & + \\ + \\ + % Check challenge and send challenge response (reveal not selected msgs) + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\gamma} & + \\ \textbf{check } \text{IsConsistentChallenge}(\rho_{RC}, \gamma) + \\ \textbf{Comment: } \text{IsConsistentChallenge}\\(\rho_{RC}, \gamma) \mapsto \{ \bot,\top \} + \\ + \\ \text{Persist refresh-challenge} \langle \rho_{RC}, \gamma \rangle + \\ S := \langle t_1, \dots, t_{\gamma-1}, t_{\gamma+1}, \dots, t_\kappa \rangle % all seeds without the gamma seed + \\ \rho_L = \langle C_p^{(0)}, D_{p(t)}, T_{\gamma},\overline{m}_\gamma \rangle + \\ \rho_{RR} = \langle T_\gamma, \overline{m}_\gamma, S \rangle + \\ \sigma_{L} = \text{Ed25519.Sign}(c_s^{(0)}, \rho_{L}) + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{\rho_{RR},\rho_L, \sigma_{L}} & + % check revealed msgs and sign coin + \\ & & \langle T'_\gamma, \overline{m}'_\gamma, S \rangle := \rho_{RR} + \\ & & \langle t_1, \dots, t_{\gamma-1}, t_{\gamma+1}, \dots, t_\kappa \rangle ) := S + \\ & & \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \sigma_L, \rho_L) + \\ & & \textbf{for} i = 1,\dots, \gamma-1, \gamma+1,\dots, \kappa + \\ & & X_i := \text{RefreshDerive}(t_i, D_{p(t)}, C_p^{(0)}) + \\ & & \langle T_i, c_s^{(i)}, C_p^{(i)}, \overline{m}_i \rangle := X_i + \\ & & \textbf{endfor} + \\ & & h_T' = H(T_1,\dots,T_{\gamma-1},T'_{\gamma},T_{\gamma+1},\dots,T_\kappa) + \\ & & h_{\overline{m}}' = H(\overline{m}_1,\dots,\overline{m}_{\gamma-1},\overline{m}'_{\gamma},\overline{m}_{\gamma+1},\dots,\overline{m}_\kappa) + \\ & & h_C' = H(h_T', h_{\overline{m}}') + \\ & & \textbf{check } h_C = h_C' + \\ & & \overline{\sigma}_C^{(\gamma)} := \overline{m}^{d_{s(t)}} + \\ & & \text{persist } \langle \rho_L, \sigma_L \rangle + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{\overline{\sigma}_C^{(\gamma)}} & + % Check coin signature and persist coin + \\ \sigma_C^{(\gamma)} := r^{-1}\overline{\sigma}_C^{(\gamma)} + \\ \textbf{check if } (\sigma_C^{(\gamma)})^{e_t} \equiv_{N_t} C_p^{(\gamma)} + \\ \text{Persist coin} \langle D_{p(t)}, c_s^{(\gamma)}, C_p^{(\gamma)}, \sigma_C^{(\gamma)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Redesigned RSA refresh protocol (reveal phase)} + \label{fig:refresh-part2-rsa-redesign} +\end{figure} + + +\section{Linking Protocol} +The changes are described in \autoref{fig:refresh-link-rsa-redesign}. +\begin{figure}[htp] + \begin{equation*} + \resizebox{1.0\textwidth}{!}{$\displaystyle + \begin{array}{ l c l } + % preliminaries + \text{Customer} & & \text{Exchange} + \\ \text{knows:} & & \text{knows:} + \\ \text{coin}_0 = \langle D_{p(0)}, c_s^{(0)}, C_p^{(0)}, \sigma_{C}^{(0)} \rangle + \\ & \xrightarrow[\rule{2.5cm}{0pt}]{C_{p(0)}} & + \\ & & L := \text{LookupLink}(C_{p(0)}) + \\ & & \textbf{Comment: } \text{LookupLink}(C_p) \mapsto \{\langle \rho_L^{(i)}, + \\ & & \sigma_L^{(i)}, \overline{\sigma}_C^{(i)} \rangle\} + \\ & \xleftarrow[\rule{2.5cm}{0pt}]{L} & + \\ \pcfor \langle \rho_{L}^{(i)}, \overline{\sigma}_L^{(i)}, \sigma_C^{(i)} \rangle \in L + \\ \langle \hat{C}_p^{(i)}, D_{p(t)}^{(i)}, T_\gamma^{(i)}, \overline{m}_\gamma^{(i)} \rangle := \rho_L^{(i)} + \\ \langle e_t^{(i)}, N_t^{(i)} \rangle := D_{p(t)}^{(i)} + \\ \textbf{check } \hat{C}_p^{(i)} \equiv C_p^{(0)} + \\ \textbf{check } \text{Ed25519.Verify}(C_p^{(0)}, \rho_{L}^{(i)}, \sigma_L^{(i)}) + \\ x_i := \text{ECDH}(c_s^{(0)}, T_{\gamma}^{(i)}) + \\ c_s^{(i)} := \text{HKDF}(256,x_i,"c") + \\ C_p^{(i)} := \text{Ed25519.GetPub}(c_s^{(i)}) + \\ b_s^{(i)} := \text{HKDF}(256, x_i, \text{"b-seed"}) + \\ r_i := \text{FDH}(b_s^{(i)}) + \\ \sigma_C^{(i)} := (r_i)^{-1} \cdot \overline{m}_\gamma^{(i)} + \\ \textbf{check } (\sigma_C^{(i)})^{e_t^{(i)}} \equiv_{N_t^{(i)}} C_p^{(i)} + \\ \text{(Re-)obtain coin} \langle D_{p(t)}^{(i)},c_s^{(i)}, C_p^{(i)}, \sigma_C^{(i)} \rangle + \end{array}$ + } + \end{equation*} + \caption{Redesigned RSA linking protocol} + \label{fig:refresh-link-rsa-redesign} +\end{figure} diff --git a/doc/cs/content/chapter_01.tex b/doc/cs/content/chapter_01.tex new file mode 100644 index 000000000..5bb354455 --- /dev/null +++ b/doc/cs/content/chapter_01.tex @@ -0,0 +1,35 @@ +%!TEX root = ../dokumentation.tex + +\chapter{Das erste Kapitel} +\section{Hello} +Erste Erwähnung eines Akronyms wird als Fußnote angezeigt. Jede weitere wird +nur verlinkt: \ac{AGPL}. Zweite Erwähnung \ac{AGPL} + +Verweise auf das Glossar: \gls{Glossareintrag}, \glspl{Glossareintrag} + +Nur erwähnte Literaturverweise werden auch im Literaturverzeichnis gedruckt: +\cite{baumgartner:2002}, \cite{dreyfus:1980} +\Gls{Glossareintrag} +Meine erste Fußnote\footnote{Ich bin eine Fußnote} + +\begin{wrapfigure}{r}{.4\textwidth} +\includegraphics[height=.4\textwidth]{taler.png} +\vspace{-15pt} +\caption{Das Logo der Musterfirma\footnotemark} +\end{wrapfigure} +%Quelle muss in Fußnote stehen (da sonst aufgrund eines Fehlers nicht kompiliert +% wird) +\footnotetext{aus \cite{mustermann:2012}} +Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der das Bild +umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der +das Bild umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer +Text, der das Bild umfließt. Ein ganz langer Text, der das Bild umfließt. Ein +ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der das Bild +umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der +das Bild umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der das Bild +umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der +das Bild umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer +Text, der das Bild umfließt. Ein ganz langer Text, der das Bild umfließt. Ein +ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der das Bild +umfließt. Ein ganz langer Text, der das Bild umfließt. Ein ganz langer Text, der +das Bild umfließt. diff --git a/doc/cs/content/withdraw_loophole_remediation.tex b/doc/cs/content/withdraw_loophole_remediation.tex new file mode 100644 index 000000000..9e466aa75 --- /dev/null +++ b/doc/cs/content/withdraw_loophole_remediation.tex @@ -0,0 +1,160 @@ +\section{Remediation of the Withdraw Loophole} +The withdraw loophole allows untaxed and untraceable payments by "misusing" the withdraw protocol. +It allows withdraw operations where owner of the resulting coins isn't the owner of the reserve that the coins where withdrawn from. +It is used for tipping and can therefore be seen as a feature. + +Using the withdraw loophole for payments is illustrated in figure \ref{fig:withdraw-loophole-exploit}. +Note that we omitted the parts leading up to the coin creation (contract, agreement of price, number of coins and their denominations). +This is how it works on a high level: +\begin{enumerate} + \item The malicous merchant generates and blinds coins, which are then transmitted to the customer + \item The customer authorizes the withdraw from his reserve by signing the blinded coins with the private key of his reserve, thus generating withdraw confirmations. + \item The withdraw confirmations are transmitted to the exchange, which generates the signatures and returns them to the malicous merchant. + \item The malicous merchant unblinds the signatures. + He is now in possession of the coin, thus the payment is completed. +\end{enumerate} + +\begin{figure}[h] + \begin{equation*} + \begin{array}{ l c l} + % preliminaries + \text{Customer} & & \text{malicous Merchant} + \\ \text{knows:} & & \text{knows:} + \\ \text{reserve keys } w_s, W_p + \\ \text{denomination public key } D_p = \langle e, N \rangle & & \text{denomination public key } D_p = \langle e, N \rangle + \\ + % generate coin + \\ & & \text{generate coin key pair:} + \\ & & c_s, C_p \leftarrow \text{Ed25519.KeyGen}() + % blind + \\ & & \text{blind:} + \\ & & r \leftarrow random \in \mathbb{Z}_N^* + \\ & & m' := \text{FDH}(N, C_p)*r^{e} \mod N + % sing with reserve sk + \\ & \xleftarrow[\rule{2cm}{0pt}]{m'} + \\ \text{sign with reserve private key:} + \\ \rho_W := \langle D_p, m' \rangle + \\ \sigma_W := \text{Ed25519.Sign}(w_s, \rho_W) + \\ & \xrightarrow[\rule{2cm}{0pt}]{ \langle W_p, \sigma_W, \rho_W \rangle } + \\ + % TODO add some kind of separator + \hline + \\ + \text{malicous Merchant} & & \text{Exchange} + \\\text{knows:} & & \text{knows:} + \\& & \text{reserve public key } W_p + \\ \text{denomination public key } D_p = \langle e, N \rangle & & \text{denomination keys } d_s, D_p + \\ + \\ & \xrightarrow[\rule{2cm}{0pt}]{ \langle W_p, \sigma_W, \rho_W \rangle } + \\ & & \langle D_p, m' \rangle := \rho_W + \\ & & \text{verify if } D_p \text{ is valid} + \\ & & \textbf{check } \text{Ed25519.Verify}(W_p, \rho_W, \sigma_W) + \\ & & \text{decrease balance if sufficient} + \\ & & \text{sign:} + \\ & & \sigma'_c := (m')^{d_s} \mod N + \\ & \xleftarrow[\rule{2cm}{0pt}]{\sigma'_c} + \\ \text{unblind:} + \\ \sigma_c := \sigma'_c*r^{-1} + \\ \text{verify signature:} + \\ \textbf{check if } \sigma_c = \text{FDH}(N, C_p) + \\ + \\ \text{resulting coin: } \langle c_s, C_p, \sigma_c, D_p \rangle + \end{array} + \end{equation*} + \caption{untaxed payment using withdraw loophole} + \label{fig:withdraw-loophole-exploit} +\end{figure} + +\subsection{Requirements For A Possible Solution} +A viable solution has to fix the withdraw loophole, while still providing a solution for tipping. In addition, Taler's security properties must not be weakened. + +The underlying problem that has to be solved is to check that the person withdrawing a coin is also the owner of the reserve used in the withdraw. +This has to be solved in a way that prevents the customer and malicious merchant to work together. + +% Requirements For A Perfect Solution} +% minimal adjustments to Taler +% Commitment to sk of Reserve -> constructed by customer (key owner) +% commitment to sk of coin +% how do we ensure that the customer is key owner? -> combine with reserve sk +% how do we verify? problems with blinding +% how do we ensure that the coin in the commitment is the coin that is signed? +% exchange must not learn anything about coin to prevent linking of withdraw and transaction + +\subsection{Discussed Solution} +For our proposed solution, a few adjustments to Taler have to be made: +\begin{itemize} + \item The withdraw confirmation must include a commitment to the public key. + This commitment must be constructed in a way that requires the customer to know the public key. + The exception to this are special tipping reserves (to preserve the tipping feature). + \item Cut-and-choose is added to the withdraw protocol. + This means that the customer has to generate the coin and withdraw confirmation $ k $ times. + The exchange will then choose one of the $ k $ sessions. + The customer has to reveal the coin public key, blinding secret and commitment for all sessions except the chosen one. + If the customer isn't able to deliver, the reserve is locked for future withdraws until the other sessions are delivered. + Cut-and-choose is introduced to verify whether the customer honestly created the commitment and used the same coin public key for the signature creation and the commitment. + If the reserve is a special tip reserve (which has to be registered), this check is omitted. + \item An additional protocol is created that transfers the remaining value of a coin back to the reserve if anyone is able to reveal the commitment from the withdrawal. + The adjustments described up to this point lead to the customer knowing all the necessary values for using this protocol. + Besides the customer, no one must be able to reproduce the commitment, except in case of a reserve key compromise. + \item Reserves are limited (usually only one, unless justified) and bound to a customer (KYC). + % this goes further than fixing the loophole. It prevents people from creating new reserves that are then to be transfered + % TODO check if there are disadvantages to this, especially regarding privacy + \item For a coin to be refreshable, it must have been seen by the exchange before, meaning that it had to be used for a payment. + The purpose of this is to prevent a malicious merchant to simply refresh a coin after withdraw to prevent the customer from reverting the withdraw. + \item For any coin used in a payment, the subtracted value must be higher that a certain threshold (set globally or per denomination). + For example, if the threshold is $ 10\% $, at least CHF 10 of a 100 CHF coin must be used for a payment. + The goal of this change is to prevent a malicious merchant from buying a very cheap article to be able to refresh the coin. +\end{itemize} + +The commitment has to fulfill the following properties: +\begin{enumerate} + \item It has to be constructed using the reserve private key and must be verifiable using the corresponding public key. + \item It has to include the coin public key. + \item It has to be constructed in a way that ensures that the customer has knowledge of the coin public key. + \item Everyone with knowledge of the two keys must be able to recreate it. +\end{enumerate} + +A possible commitment that partially satisfies the properties can be constructed by hashing a signature of the coin's public key: +\begin{equation*} + H( \text{Ed25519.Sign} (w_w, C_p) ) +\end{equation*} +Note that the PureEdDSA variant of Ed25519 has to be used for this. +This variant doesn't hash the message before signing (see \cite{rfc8032} for further details).\\ +It is still possible for a customer and a malicious merchant to construct the commitment without the customer gaining knowledge of the coin public key. +However, the customer has to share one half of the hash of the reserve private key (which is practically one half of the private key, refer to section \ref{sec:eddsa-signature-creation} for details about EdDSA signature creation). + +% was passiert wenn im Verhör und gezwungen wird, Keys herauszurücken? + +There is one drawback to this solution: +In case of a reserve key compromise, coins generated by withdraw operation (not refreshed ones) can be linked to withdraw operations, thus revealing relationships between reserves and payments. +This is because an adversary (exchange or auditor) in possession of a reserve private key and coin public keys can calculate $ \text{H(Ed25519.Sign}(w_s, C_p)) $ and check in the database if there is a corresponding withdraw operation, thus linking reserve and coin. + +\subsubsection{Discussion} +This is not perfect solution. +It is designed to make untaxed payments using the withdraw loophole less attractive to use for merchants. +If accepted, it should only be used in deployments where the withdraw loophole has to be prohibited.\\ +The proposed modifications achieve that a malicious merchant, who wants to perform payments using the withdraw loophole, has to accept one of these drawbacks: +\begin{itemize} + \item He has to accept that the customer is able to revert the payment. + \item He has to spend the coins fully.\\ + If he is registered as a merchant at an exchange, he can perform payments to himself to launder the money. + Here, Talers \ac{AML} capabilities come into play.\\ + The other possibility is to buy goods at other merchants. + These goods then have to be liquidated, which requires effort. + This wouldn't be a problem (for the malicous merchant) if cryptocurrency can be bought using Taler. + \item He has to spend the coins partially to be able to refresh them (thus preventing payment reversion by the customer). + The goods that were bought using the coin fraction then would have to be liquidated (see previous point). + \item He has to add the threshold value that is lost in order to refresh the coin into the price for payments. +\end{itemize} + +The commitment added to the withdrawal weakens the privacy of coins. +Blinding guarantees everlasting privacy, which would be neutralized by the commitment. + +The added cut-and-choose makes withdrawing more intensive, which leads to increased infrastructure requirements (and therefore costs). + +The added threshold makes coin spending less flexible. +Wallets either have to contain more coins to guarantee that there is always a coin (or multiple) available to guarantee a payment without violating the threshold limitations. +The other variant is that wallets refrain from withdrawing coins with big(ger) denominations, which leads to bigger sums of coins used per payment. + +This discussed solution is submitted to the Taler team as a part of the thesis documentation, upon which they can review the protocol changes and decide whether to pursue further. +Therefore, the solution will not be implemented during this thesis. diff --git a/doc/cs/content/x_taler.tex b/doc/cs/content/x_taler.tex new file mode 100644 index 000000000..d04fe84cf --- /dev/null +++ b/doc/cs/content/x_taler.tex @@ -0,0 +1,373 @@ +\chapter{Taler} + +\section{Taler Architecture} + +\subsection{Auditor} +The following text is cited from section 4.4 in \cite{dold:the-gnu-taler-system} +\begin{center} + \textit{ + "The auditor consists of two processes that are regularly run and generate auditing reports. + Both processes access the exchange’s database, either directly (for exchange-internal auditing as part if its operational security) or over a replica (in the case of external auditors). + The taler-wire-auditor process checks that the incoming and outgoing transfers recorded in the exchange’s database match wire transfers of the underlying bank account. + To access the transaction history (typically recorded by the bank), the wire auditor uses a wire plugin, with the same interface and implementation as the exchange’s wire plugins. + The taler-auditor process generates a report with the following information: + } +\end{center} + +\begin{itemize} + \item \textit{Do the operations stored in a reserve’s history match the reserve’s balance?} + \item \textit{Did the exchange record outgoing transactions to the right merchant for deposits after the deadline for the payment was reached?} + \item \textit{Do operations recorded on coins (deposit, refresh, refund) match the remaining value on the coin?} + \item \textit{Do operations respect the expiration of denominations?} + \item \textit{For a denomination, is the number of pairwise different coin public keys recorded in deposit/refresh operations smaller or equal to the number of blind signatures recorded in withdraw/refresh operations? If this invariant is violated, the corresponding denomination must be revoked.} + \item \textit{What is the income if the exchange from different fees?} +\end{itemize} + +\begin{center} + \textit{ + \dots + The auditor exposes a web server with the taler-auditor-httpd process. + Currently, it only shows a website that allows the customer to add the auditor to the list of trusted auditors in their wallet. + In future versions, the auditor will also have HTTP endpoints that allow merchants to submit samples of deposit confirmations, which will be checked against the deposit permissions in the exchange’s database to detect compromised signing keys or missing writes. + Furthermore, in deployments that require the merchant to register with the exchange beforehand, the auditor also offers a list of exchanges it audits, so that the merchant backend can automatically register with all exchanges it transitively trusts." + } +\end{center} +Some details were left out (see at the dots) and can be read in section 4.4 in \cite{dold:the-gnu-taler-system} + +\subsubsection{Technical Details} +Documentation: \cite{taler-documentation:auditor-operator-manual} \\ +Git Repositories: +\begin{itemize} + \item Main repository: \cite{taler-git:exchange} (Part of exchange repository, inside ./src/auditor and ./src/auditordb) + \item Auditor's public website: \cite{taler-git:auditor} +\end{itemize} +Language: C \\ +Dependencies: +\begin{itemize} + \item GNUnet >= 0.14.0 + \item GNU libmicrohttpd >= 0.9.71 + \item Postgres >= 9.6, including libpq + \item libjansson >= 2.7 + \item libargon2 >= 20171227 + \item libsodium >= 1.0 + \item libgcrypt >= 1.6 + \item libqrencode >= 4.0.0 + \item libcurl >= 7.26 (or libgnurl >= 7.26) + \item GNU libunistring >= 0.9.3 + \item libsqlite3 >= 3.16.2 +\end{itemize} +The auditor API is implemented as REST API and uses \ac{JSON} as message format. +The auditor does not implement HTTPS (TLS), instead it recommends using a HTTP reverse Proxy that offers TLS termination. +By delegating the responsibility for TLS termination, the auditor implementation becomes lighter. + +There are a lot more technical details written in the documentation linked above and in the README files. +Since Taler is actively developed and technical details could change, we refer to this documentation. + +\subsection{Exchange} +The following text is cited from section 4.3 in \cite{dold:the-gnu-taler-system} +\begin{center} + \textit{ + "The exchange consists of three independent processes: + } +\end{center} +\begin{itemize} + \item \textit{The taler-exchange-httpd process handles HTTP requests from clients, mainly merchants and wallets.} + \item \textit{The taler-exchange-wirewatch process watches for wire transfers to the exchange’s bank account and updates reserves based on that.} + \item \textit{The taler-exchange-aggregator process aggregates outgoing transactions to merchants.} +\end{itemize} + +\begin{center} + \textit{ + All three processes exchange data via the same database. + Only taler-exchange-httpd needs access to the exchanges online signing keys and denomination keys. + The database is accessed via a Taler-specific database abstraction layer. + Different databases can be supported via plugins; at the time of writing this, only a PostgreSQL plugin has been implemented. + Wire plugins are used as an abstraction to access the account layer that Taler runs on. + Specifically, the wirewatch process uses the plugin to monitor incoming transfers, and the aggregator process uses the wire plugin to make wire transfers to merchants. + The following APIs are offered by the exchange: + } + + \textbf{\textit{Announcing keys, bank accounts and other public information}}\\ + \textit{ + The exchange offers the list of denomination keys, signing keys, auditors, supported bank accounts, revoked keys and other general information needed to use the exchange’s services via the /keys and /wire APIs. + } + + \textbf{\textit{Reserve status and withdrawal}}\\ + \textit{ + After having wired money to the exchange, the status of the reserve can be checked via the /reserve/status API. Since the wire transfer usually takes some time to arrive at the exchange, wallets should periodically poll this API, and initiate a withdrawal with /reserve/withdraw once the exchange received the funds. + } + + \textbf{\textit{Deposits and tracking}}\\ + \textit{ + Merchants transmit deposit permissions they have received from customers to the exchange via the/deposit API. Since multiple deposits are aggregated into one wire transfer, the merchant additionally can use the exchange’s /track/transfer API that returns the list of deposits for an identifier included in the wire transfer to the merchant, as well as the /track/transaction API to look up which wire transfer included the payment for a given deposit. + } + + \textbf{\textit{Refunds}}\\ + \textit{ + The refund API (/refund) can “undo” a deposit if the merchant gave their signature, and the aggregation deadline for the payment has not occurred yet. + } + + \textbf{\textit{Emergency payback}}\\ + \textit{ + The emergency payback API (/payback) allows customers to be compensated for coins whose denomination key has been revoked. + Customers must send either a full withdrawal transcript that includes their private blinding factor, or a refresh transcript (of a refresh that had the revoked denominations as one of the targets) that includes blinding factors. + In the former case, the reserve is credited, in the latter case, the source coin of the refresh is refunded and can be refreshed again." + } +\end{center} + +Additional information for how the exchange generates new denomination and signing keys can be found in the end of section 4.3 of \cite{dold:the-gnu-taler-system}. + +\begin{figure}[h!] + \centering + \includegraphics[height=0.5\textwidth]{taler-exchange.png} + \caption{Architecture of the Taler Exchange reference implementation. Source: \cite{dold:the-gnu-taler-system}} + \label{fig:taler-arch-exchange} +\end{figure} + +\subsubsection{Technical Details} + +Documentation: \cite{taler-documentation:exchange-operator-manual} \\ +Git Repository: Main repository: \cite{taler-git:exchange} \\ +Language: C \\ +Dependencies: +\begin{itemize} + \item GNUnet >= 0.14.0 + \item GNU libmicrohttpd >= 0.9.71 + \item Postgres >= 9.6, including libpq + \item libjansson >= 2.7 + \item libargon2 >= 20171227 + \item libsodium >= 1.0 + \item libgcrypt >= 1.6 + \item libqrencode >= 4.0.0 + \item libcurl >= 7.26 (or libgnurl >= 7.26) + \item GNU libunistring >= 0.9.3 + \item libsqlite3 >= 3.16.2 +\end{itemize} +The exchange’s API is implemented as REST API and uses \ac{JSON} as message format. + +There are a lot more technical details written in the documentation linked above and in the README files. +Since Taler is actively developed and technical details could change, we refer to this documentation. + +\subsection{Merchant} +The following text is cited from section 4.5 in \cite{dold:the-gnu-taler-system} +\begin{center} + \textit{ + "The Taler merchant backend is a component that abstracts away the details of processing Taler payments and provides a simple HTTP API. + The merchant backend handles cryptographic operations (signature verification, signing), secret management and communication with the exchange. + The backend API (see \url{https://docs.taler.net/api/}) is divided into two types of HTTP endpoints: + } +\end{center} + +\begin{enumerate} + \item \textit{Functionality that is accessed internally by the merchant. + These API stypically require authentication and/or are only accessible from within the private network of the merchant.} + \item \textit{Functionality that is exposed publicly on the Internet and accessed by the customer’s wallet and browser.} +\end{enumerate} + +\begin{center} + \textit{ + A typical merchant has a storefront component that customers visit with their browser, as well as a back office component that allows the merchant to view information about payments that customers made and that integrates with other components such as order processing and shipping." + } +\end{center} + +\subsubsection{Processing Payments} +\begin{center} + \textit{ + "To process a payment, the storefront first instructs the backend to create an order. + The order contains information relevant to the purchase, and is in fact a subset of the information contained in the contract terms. + The backend automatically adds missing information to the order details provided by the storefront. + The full contract terms can only be signed once the customer provides the claim public key for the contract.\\ + Each order is uniquely identified by an order ID, which can be chosen by the storefront or automatically generated by the backend. + The order ID can be used to query the status of the payment. + If the customer did not pay for an order ID yet, the response from the backend includes a payment redirect URL. + The storefront can redirect the customer to this payment redirect URL; visiting the URL will trigger the customer’s browser/wallet to prompt for a payment.\\ + To simplify the implementation of the storefront, the merchant backend can serve a page to the customer’s browser that triggers the payment via the HTTP402 status code and the corresponding headers, and provides a fallback (in the form of a taler:pay link) for loosely integrated browsers. + When checking the status of a payment that is not settled yet, the response from the merchant backend will contains a payment redirect URL. + The storefront redirects the browser to this URL, which is served by the merchant backend and triggers the payment. + \dots " + } +\end{center} + +\subsubsection{Back Office APIs} +\begin{center} + \textit{ + "The back office API allows the merchant to query information about the history and status of payments, as well as correlate wire transfers to the merchant’s bank account with the respective GNU Taler payment. + This API is necessary to allow integration with other parts of the merchant’s e-commerce infrastructure." + } +\end{center} + +% Nachfolgende Section nicht notwendig. +% \subsubsection{Example Merchant Frontends} +% This section is included to provide an overview of the reference implementation for the merchant. +% This helps to get a better understanding of how a merchant could potentially look like. +% Note that the actual code could differ from the cited part. +% The actual code can be found in \url{git.taler.net} +% \begin{center} +% \textit{ +% We implemented the following applications using the merchant backend API. +% } + +% \textit{\textbf{Blog Merchant}}\\ +% \textit{ +% The blog merchant’s landing page has a list of article titles with a teaser. +% When following the link to the article, the customer is asked to pay to view the article. +% } + +% \textit{\textbf{Donations}}\\ +% \textit{ +% The donations frontend allows the customer to select a project to donate to. +% The fulfillment page shows a donation receipt. +% } + +% \textit{\textbf{Codeless Payments}}\\ +% \textit{ +% The codeless payment frontend is a prototype for a user interface that allows merchants to sell products on their website without having to write code to integrate with the merchant backend. +% Instead, the merchant uses a web interface to manage products and their available stock. +% The codeless payment frontend then creates an HTML snippet with a payment button that the merchant can copy-and-paste integrate into their storefront. +% } + +% \textit{\textbf{Survey}}\\ +% \textit{ +% The survey frontend showcases the tipping functionality of GNU Taler. +% The user fills out a survey and receives a tip for completing it. +% } + +% \textit{\textbf{Back Office}}\\ +% \textit{ +% The example back-office application shows the history and status of payments processed by the merchant. +% } +% \end{center} + +\begin{figure}[h!] + \centering + \includegraphics[height=0.5\textwidth]{taler-merchant.png} + \caption{Architecture Taler Merchant reference implementation. Source: \cite{dold:the-gnu-taler-system}} + \label{fig:taler-arch-merchant} +\end{figure} + +\subsubsection{Technical Details} + +Documentation: \cite{taler-documentation:merchant-backend-operator-manual} \\ +API Documentation: \cite{taler-documentation:merchant-api} \\ +Back-office Documentation: \cite{taler-documentation:back-office} \\ +Point-of-Sales Documentation: \cite{taler-documentation:pos-manual} \\ +Git Repositories: +\begin{itemize} +\item Backend: \cite{taler-git:merchant} +\item Backoffice: \cite{taler-git:backoffice} +\item Point-of-Sales App: \cite{taler-git:android} (part of android repo) +\end{itemize} +Language: C (Backend), Kotlin (\ac{PoS}), [Python, Javascript] (Backoffice)\\ +Dependencies: +\begin{itemize} + \item GNUnet >= 0.14.0 + \item GNU libmicrohttpd >= 0.9.71 + \item Postgres >= 9.6, including libpq + \item libjansson >= 2.7 + \item libargon2 >= 20171227 + \item libsodium >= 1.0 + \item libgcrypt >= 1.6 + \item libqrencode >= 4.0.0 + \item libcurl >= 7.26 (or libgnurl >= 7.26) + \item GNU libunistring >= 0.9.3 + \item libsqlite3 >= 3.16.2 + \item Flask (Backoffice) +\end{itemize} +Frontend Repositories: +\begin{itemize} + \item Payments with Django: \cite{taler-git:django-payments} + \item Wordpress woocommerce plugin: \cite{taler-git:woocommerce} + \item Saleor Frontend: \cite{taler-git:saleor} + \item Demo Frontends: \cite{taler-git:merchant-demos} +\end{itemize} +The merchant’s API is implemented as REST API and uses \ac{JSON} as message format. +The \ac{PoS} app is for the merchant to process customer's orders by adding or removing products, calculating the amount owed by the customer or letting the customer make a Taler payment via QR code or NFC. +The back office Web service allows a merchant to check status of their Taler transactions. +There are already a lot of demo pages and integrations for different e-commerce solutions. + +There are a lot more technical details written in the documentation linked above and in the README files. +Since Taler is actively developed and technical details could change, we refer to this documentation. + +\subsection{Wallet} +The following text is cited from section 4.6 in \cite{dold:the-gnu-taler-system} +\begin{center} + \textit{ + "The wallet manages the customer’s reserves and coins, lets the customer view and pay for contracts from merchants. \dots + The reference implementation of the GNU Taler wallet is written in the Type-Script language against the WebExtension API, a cross-browser mechanism for browser extensions. + The reference wallet is a “tightly integrated” wallet, as it directly hooks into the browser to process responses with the HTTP status code“402 Payment Required”.\\ + Many cryptographic operations needed to implement the wallet are not commonly available in a browser environment. + We cross-compile the GNU Taler utility library written in C as well as its dependencies (such as libgcrypt) to asm.js (and WebAssembly on supported platforms) using the LLVM-based emscripten toolchain. + Cryptographic operations run in an isolated process implemented as a WebWorker. + This design allows the relatively slow cryptographic operations to run concurrently in the background in multiple threads. + Since the crypto WebWorkers are started on-demand, the wallet only uses minimal resources when not actively used." + } +\end{center} + +\subsubsection{Optimizations} +\begin{center} + \textit{ + "To improve the perceived performance of cryptographic operations, the wallet optimistically creates signatures in the background while the user is looking at the “confirm payment” dialog. + If the user does not accept the contract, these signatures are thrown away instead of being sent to the merchant. + This effectively hides the latency of the most expensive cryptographic operations, as they are done while the user consciously needs to make a decision on whether to proceed with a payment." + } +\end{center} + +\subsubsection{Wallet Detection} +\begin{center} + \textit{ + " \dots + Browser fingerprinting is a concern with any additional APIs made available to websites, either by the browser itself or by browser extensions. + Since a website can simply try to trigger a payment to determine whether a tightly integrated Taler wallet is installed, one bit of additional fingerprinting information is already available through the usage of Taler. + The dynamic detection methods do not, however, expose any information that is not already available to websites by signaling the wallet through HTTP headers." + } +\end{center} + +\subsubsection{Further Wallet Features} +More information about other Wallet Features like coin selection, wallet liquidation and wallet signaling can be found in sections 4.6.2, 4.6.5 and 4.6.6 of \cite{dold:the-gnu-taler-system}. + +\begin{figure}[h!] + \centering + \includegraphics[height=0.5\textwidth]{taler-wallet.png} + \caption{Architecture of the Taler Wallet reference implementation. Source: \cite{dold:the-gnu-taler-system}} + \label{fig:taler-wallet-reference-impl} +\end{figure} + +\subsubsection{Technical Details} + +Documentation: \cite{taler-documentation:wallet-developer-manual} \\ +Wallet-CLI documentation: \cite{taler-documentation:wallet-cli-manual} \\ +Git Repository: +\begin{itemize} + \item Main repository: \cite{taler-git:wallet-core} \\ + This Repository includes the wallet-core and the implementations for the web extension and CLI. + \item Android app: \cite{taler-git:android} + \item iOS app: \cite{taler-git:ios} +\end{itemize} +Language: Typescript, Javascript (wallet-core, web extension), Kotlin (Android app), Swift (iOS app)\\ +Dependencies: +\begin{itemize} + \item prettier + \item rimraf + \item rollup + \item typescript + \item ava + \item esbuild + \item axios + \item tslib + \item cancellationtoken + \item minimatch + \item source-map-support + \item big-integer + \item fflate + \item esm + \item jed + \item nyc + \item po2json + \item typedoc + \item api-extractor +\end{itemize} + +There are a lot more technical details written in the documentation linked above and in the README files. +Since Taler is actively developed and technical details could change, we refer to this documentation. + + diff --git a/doc/cs/images/bfh_logo.png b/doc/cs/images/bfh_logo.png new file mode 100644 index 000000000..e3aba1175 Binary files /dev/null and b/doc/cs/images/bfh_logo.png differ diff --git a/doc/cs/images/diagram-simple.png b/doc/cs/images/diagram-simple.png new file mode 100644 index 000000000..d6ad2921e Binary files /dev/null and b/doc/cs/images/diagram-simple.png differ diff --git a/doc/cs/images/logo-2021.png b/doc/cs/images/logo-2021.png new file mode 100644 index 000000000..ea599bdab Binary files /dev/null and b/doc/cs/images/logo-2021.png differ diff --git a/doc/cs/images/projectplan.png b/doc/cs/images/projectplan.png new file mode 100644 index 000000000..edad872b2 Binary files /dev/null and b/doc/cs/images/projectplan.png differ diff --git a/doc/cs/images/taler-exchange.png b/doc/cs/images/taler-exchange.png new file mode 100644 index 000000000..2e898b0ac Binary files /dev/null and b/doc/cs/images/taler-exchange.png differ diff --git a/doc/cs/images/taler-merchant.png b/doc/cs/images/taler-merchant.png new file mode 100644 index 000000000..15b746129 Binary files /dev/null and b/doc/cs/images/taler-merchant.png differ diff --git a/doc/cs/images/taler-pki.png b/doc/cs/images/taler-pki.png new file mode 100644 index 000000000..f72d42315 Binary files /dev/null and b/doc/cs/images/taler-pki.png differ diff --git a/doc/cs/images/taler-wallet.png b/doc/cs/images/taler-wallet.png new file mode 100644 index 000000000..234d8a0e7 Binary files /dev/null and b/doc/cs/images/taler-wallet.png differ diff --git a/doc/cs/images/taler_bigger.png b/doc/cs/images/taler_bigger.png new file mode 100644 index 000000000..cd55fa643 Binary files /dev/null and b/doc/cs/images/taler_bigger.png differ diff --git a/doc/cs/images/taler_cut_and_choose.png b/doc/cs/images/taler_cut_and_choose.png new file mode 100644 index 000000000..47ad4d0d0 Binary files /dev/null and b/doc/cs/images/taler_cut_and_choose.png differ diff --git a/doc/cs/images/taler_refresh_link_threat.png b/doc/cs/images/taler_refresh_link_threat.png new file mode 100644 index 000000000..03d0804fb Binary files /dev/null and b/doc/cs/images/taler_refresh_link_threat.png differ diff --git a/doc/cs/images/taler_refresh_transfer_key.png b/doc/cs/images/taler_refresh_transfer_key.png new file mode 100644 index 000000000..d75360f28 Binary files /dev/null and b/doc/cs/images/taler_refresh_transfer_key.png differ diff --git a/doc/cs/thesis.tex b/doc/cs/thesis.tex new file mode 100644 index 000000000..1e4bfb87e --- /dev/null +++ b/doc/cs/thesis.tex @@ -0,0 +1,93 @@ +%============================ MAIN DOCUMENT ================================ +% define document class +\documentclass[ + a4paper % paper format +% ,10.5pt % fontsize +% ,BCOR=18mm % Binding correction +% ,twoside +% ,headings=openright + ,bibliography=totoc % If enabled add bibliography to TOC + ,class=scrreprt % If removed, makes book format (1 side left, 1 right) + ,listof=totoc % If enabled add lists to TOC +% ,bilingual + ,monolingual +% ,invert-title % Invert the BFH colors +]{bfhthesis} % KOMA-script report + +\input{ads/header.tex} + +\begin{document} + +\frontmatter + + +\input{variable.sty} + +%---------------- BFH tile page ----------------------------------------- +\maketitle + +% Abstract +\input{ads/abstract} + +%------------ TABLEOFCONTENTS ---------------- +\tableofcontents + +%------------ START MAIN PART ---------------- +\mainmatter + +%------------ Introduction +\input{content/1_introduction.tex} + +%------------ Project management +% \input{content/2_project_management.tex} + +%------------ Preliminaries +\input{content/3_preliminaries.tex} + +%------------ Execution +\input{content/4_execution.tex} + +%------------ Discussion +\input{content/5_discussion.tex} + +%------------ Conclusion +\input{content/6_conclusion.tex} + + + +%------------ Eidesstattliche Erklärung +\includepdf[pages=1]{ads/Erklaerung} +%------------ History +% \input{ads/history} + +%------------ Abbildungsverzeichnis +%\cleardoublepage +\listoffigures + +%------------ Tabellenverzeichnis +%\cleardoublepage +\listoftables + +% TODO +%------------ Quellcodeverzeichnis +% \cleardoublepage + \phantomsection \label{listoflist} + \addcontentsline{toc}{chapter}{List of listings} + \lstlistoflistings + +%------------ Literaturverzeichnis +%\cleardoublepage +\printbibliography + +%------------ Abkürzungsverzeichnis +%\cleardoublepage +\phantomsection \label{listofacs} +\addcontentsline{toc}{chapter}{Abbreviations} +\input{ads/abbreviation} + +%------------ Glossar +\printglossary[style=altlist,title=Glossary] + +%------------ Anhang +\input{content/appendix.tex} +\end{document} diff --git a/doc/cs/variable.sty b/doc/cs/variable.sty new file mode 100644 index 000000000..18ae77a7c --- /dev/null +++ b/doc/cs/variable.sty @@ -0,0 +1,15 @@ +\title{Adding Schnorr's Blind Signature in Taler} +\subtitle{An improved Taler Blind Signature System} +\author{{Gian Demarmels}, {Lucien Heuzeveldt}} +\institution{Bern University of Applied Science} +\department{Engineering and Computer Sciences} +\institute{Institute for Cybersecurity and Engineering ICE} +\version{1.0} +\titlegraphic{\includegraphics[width=\width]{logo-2021.png}} +\advisor{Prof. Dr. Emmanuel Benoist} +\expert{Elektronikingenieur HTL Daniel Voisard} +\degreeprogram{Bachelor of Science in Computer Science} +\setupSignature{ + G. Demarmels={\includegraphics[width=\linewidth]{logo-2021.png}}, + L. Heuzeveldt={\includegraphics[width=\linewidth]{bfh_logo.png}\vskip-\baselineskip} +} diff --git a/src/auditor/generate-auditor-basedb.conf b/src/auditor/generate-auditor-basedb.conf index e5de0b592..5540aa3b8 100644 --- a/src/auditor/generate-auditor-basedb.conf +++ b/src/auditor/generate-auditor-basedb.conf @@ -106,6 +106,7 @@ fee_withdraw = TESTKUDOS:0.01 fee_deposit = TESTKUDOS:0.01 fee_refresh = TESTKUDOS:0.01 fee_refund = TESTKUDOS:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_ct_10] @@ -117,6 +118,7 @@ fee_withdraw = TESTKUDOS:0.01 fee_deposit = TESTKUDOS:0.01 fee_refresh = TESTKUDOS:0.03 fee_refund = TESTKUDOS:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_1] @@ -128,6 +130,7 @@ fee_withdraw = TESTKUDOS:0.02 fee_deposit = TESTKUDOS:0.02 fee_refresh = TESTKUDOS:0.03 fee_refund = TESTKUDOS:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_2] @@ -139,6 +142,7 @@ fee_withdraw = TESTKUDOS:0.03 fee_deposit = TESTKUDOS:0.03 fee_refresh = TESTKUDOS:0.04 fee_refund = TESTKUDOS:0.02 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_4] @@ -150,6 +154,7 @@ fee_withdraw = TESTKUDOS:0.03 fee_deposit = TESTKUDOS:0.03 fee_refresh = TESTKUDOS:0.04 fee_refund = TESTKUDOS:0.02 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_5] @@ -161,6 +166,7 @@ fee_withdraw = TESTKUDOS:0.01 fee_deposit = TESTKUDOS:0.01 fee_refresh = TESTKUDOS:0.03 fee_refund = TESTKUDOS:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_8] @@ -172,6 +178,7 @@ fee_withdraw = TESTKUDOS:0.05 fee_deposit = TESTKUDOS:0.02 fee_refresh = TESTKUDOS:0.03 fee_refund = TESTKUDOS:0.04 +CIPHER = RSA rsa_keysize = 1024 [coin_kudos_10] @@ -183,6 +190,31 @@ fee_withdraw = TESTKUDOS:0.01 fee_deposit = TESTKUDOS:0.01 fee_refresh = TESTKUDOS:0.03 fee_refund = TESTKUDOS:0.01 +CIPHER = RSA +rsa_keysize = 1024 + +[coin_kudos_ct_1] +value = TESTKUDOS:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = TESTKUDOS:0.01 +fee_deposit = TESTKUDOS:0.01 +fee_refresh = TESTKUDOS:0.01 +fee_refund = TESTKUDOS:0.01 +CIPHER = RSA +rsa_keysize = 1024 + +[coin_kudos_ct_10] +value = TESTKUDOS:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = TESTKUDOS:0.01 +fee_deposit = TESTKUDOS:0.01 +fee_refresh = TESTKUDOS:0.03 +fee_refund = TESTKUDOS:0.01 +CIPHER = RSA rsa_keysize = 1024 [benchmark] diff --git a/src/auditor/report-lib.c b/src/auditor/report-lib.c index 0dea786da..97270ffbe 100644 --- a/src/auditor/report-lib.c +++ b/src/auditor/report-lib.c @@ -89,13 +89,6 @@ static struct GNUNET_SIGNAL_Context *sig_int; static struct GNUNET_SIGNAL_Context *sig_term; -/** - * Test if the audit should be aborted because the user - * pressed CTRL-C. - * - * @return false to continue the audit, true to terminate - * cleanly as soon as possible - */ bool TALER_ARL_do_abort (void) { @@ -103,12 +96,6 @@ TALER_ARL_do_abort (void) } -/** - * Add @a object to the report @a array. Fail hard if this fails. - * - * @param array report array to append @a object to - * @param object object to append, should be check that it is not NULL - */ void TALER_ARL_report (json_t *array, json_t *object) @@ -183,14 +170,6 @@ add_denomination ( } -/** - * Obtain information about a @a denom_pub. - * - * @param dh hash of the denomination public key to look up - * @param[out] issue set to detailed information about @a denom_pub, NULL if not found, must - * NOT be freed by caller - * @return transaction status code - */ enum GNUNET_DB_QueryStatus TALER_ARL_get_denomination_info_by_hash ( const struct TALER_DenominationHash *dh, @@ -262,15 +241,6 @@ TALER_ARL_get_denomination_info_by_hash ( } -/** - * Obtain information about a @a denom_pub. - * - * @param denom_pub key to look up - * @param[out] issue set to detailed information about @a denom_pub, NULL if not found, must - * NOT be freed by caller - * @param[out] dh set to the hash of @a denom_pub, may be NULL - * @return transaction status code - */ enum GNUNET_DB_QueryStatus TALER_ARL_get_denomination_info ( const struct TALER_DenominationPublicKey *denom_pub, @@ -298,7 +268,7 @@ TALER_ARL_get_denomination_info ( * #GNUNET_NO if we had an error on commit (retry may help) * #GNUNET_SYSERR on hard errors */ -static int +static enum GNUNET_GenericReturnValue transact (TALER_ARL_Analysis analysis, void *analysis_cls) { @@ -369,14 +339,7 @@ transact (TALER_ARL_Analysis analysis, } -/** - * Initialize DB sessions and run the analysis. - * - * @param ana analysis to run - * @param ana_cls closure for @a ana - * @return #GNUNET_OK on success - */ -int +enum GNUNET_GenericReturnValue TALER_ARL_setup_sessions_and_run (TALER_ARL_Analysis ana, void *ana_cls) { @@ -424,19 +387,6 @@ test_master_present (void *cls, } -/** - * Perform addition of amounts. If the addition fails, logs - * a detailed error and calls exit() to terminate the process (!). - * - * Do not call this function directly, use #TALER_ARL_amount_add(). - * - * @param[out] sum where to store @a a1 + @a a2, set to "invalid" on overflow - * @param a1 first amount to add - * @param a2 second amount to add - * @param filename where is the addition called - * @param functionname name of the function where the addition is called - * @param line line number of the addition - */ void TALER_ARL_amount_add_ (struct TALER_Amount *sum, const struct TALER_Amount *a1, @@ -485,19 +435,6 @@ TALER_ARL_amount_add_ (struct TALER_Amount *sum, } -/** - * Perform subtraction of amounts. If the subtraction fails, logs - * a detailed error and calls exit() to terminate the process (!). - * - * Do not call this function directly, use #TALER_ARL_amount_subtract(). - * - * @param[out] diff where to store (@a a1 - @a a2) - * @param a1 amount to subtract from - * @param a2 amount to subtract - * @param filename where is the addition called - * @param functionname name of the function where the addition is called - * @param line line number of the addition - */ void TALER_ARL_amount_subtract_ (struct TALER_Amount *diff, const struct TALER_Amount *a1, @@ -546,24 +483,6 @@ TALER_ARL_amount_subtract_ (struct TALER_Amount *diff, } -/** - * Perform subtraction of amounts. Negative results should be signalled by the - * return value (leaving @a diff set to 'invalid'). If the subtraction fails - * for other reasons (currency mismatch, normalization failure), logs a - * detailed error and calls exit() to terminate the process (!). - * - * Do not call this function directly, use #TALER_ARL_amount_subtract_neg(). - * - * @param[out] diff where to store (@a a1 - @a a2) - * @param a1 amount to subtract from - * @param a2 amount to subtract - * @param filename where is the addition called - * @param functionname name of the function where the addition is called - * @param line line number of the addition - * @return #TALER_ARL_SR_INVALID_NEGATIVE if the result was negative (and @a diff is now invalid), - * #TALER_ARL_SR_ZERO if the result was zero, - * #TALER_ARL_SR_POSITIVE if the result is positive - */ enum TALER_ARL_SubtractionResult TALER_ARL_amount_subtract_neg_ (struct TALER_Amount *diff, const struct TALER_Amount *a1, @@ -622,13 +541,7 @@ handle_sigint (void) } -/** - * Setup global variables based on configuration. - * - * @param c configuration to use - * @return #GNUNET_OK on success - */ -int +enum GNUNET_GenericReturnValue TALER_ARL_init (const struct GNUNET_CONFIGURATION_Handle *c) { TALER_ARL_cfg = c; @@ -822,11 +735,6 @@ TALER_ARL_init (const struct GNUNET_CONFIGURATION_Handle *c) } -/** - * Generate the report and close connectios to the database. - * - * @param report the report to output, may be NULL for no report - */ void TALER_ARL_done (json_t *report) { diff --git a/src/auditor/report-lib.h b/src/auditor/report-lib.h index 3f4489763..8ef7e048a 100644 --- a/src/auditor/report-lib.h +++ b/src/auditor/report-lib.h @@ -276,7 +276,7 @@ TALER_ARL_amount_subtract_neg_ (struct TALER_Amount *diff, * @param ana_cls closure for @a ana * @return #GNUNET_OK on success */ -int +enum GNUNET_GenericReturnValue TALER_ARL_setup_sessions_and_run (TALER_ARL_Analysis ana, void *ana_cls); @@ -298,7 +298,7 @@ TALER_ARL_do_abort (void); * @param c configuration to use * @return #GNUNET_OK on success */ -int +enum GNUNET_GenericReturnValue TALER_ARL_init (const struct GNUNET_CONFIGURATION_Handle *c); diff --git a/src/auditor/taler-auditor-httpd_deposit-confirmation.c b/src/auditor/taler-auditor-httpd_deposit-confirmation.c index 694753c8d..7f4d4286c 100644 --- a/src/auditor/taler-auditor-httpd_deposit-confirmation.c +++ b/src/auditor/taler-auditor-httpd_deposit-confirmation.c @@ -221,20 +221,6 @@ verify_and_execute_deposit_confirmation ( } -/** - * Handle a "/deposit-confirmation" request. Parses the JSON, and, if - * successful, passes the JSON data to #verify_and_execute_deposit_confirmation() - * to further check the details of the operation specified. If - * everything checks out, this will ultimately lead to the "/deposit-confirmation" - * being stored in the database. - * - * @param rh context of the handler - * @param connection the MHD connection to handle - * @param[in,out] connection_cls the connection's closure (can be updated) - * @param upload_data upload data - * @param[in,out] upload_data_size number of bytes (left) in @a upload_data - * @return MHD result code - */ MHD_RESULT TAH_DEPOSIT_CONFIRMATION_handler (struct TAH_RequestHandler *rh, struct MHD_Connection *connection, @@ -323,9 +309,6 @@ TAH_DEPOSIT_CONFIRMATION_handler (struct TAH_RequestHandler *rh, } -/** - * Initialize subsystem. - */ void TEAH_DEPOSIT_CONFIRMATION_init (void) { @@ -335,9 +318,6 @@ TEAH_DEPOSIT_CONFIRMATION_init (void) } -/** - * Shut down subsystem. - */ void TEAH_DEPOSIT_CONFIRMATION_done (void) { diff --git a/src/auditor/taler-helper-auditor-coins.c b/src/auditor/taler-helper-auditor-coins.c index 5bb9ae3ea..2ed8e5a15 100644 --- a/src/auditor/taler-helper-auditor-coins.c +++ b/src/auditor/taler-helper-auditor-coins.c @@ -1086,9 +1086,6 @@ struct RevealContext * @param cls closure with a `struct RevealContext *` in it * @param num_freshcoins size of the @a rrcs array * @param rrcs array of @a num_freshcoins information about coins to be created - * @param num_tprivs number of entries in @a tprivs, should be #TALER_CNC_KAPPA - 1 - * @param tprivs array of @e num_tprivs transfer private keys - * @param tp transfer public key information */ static void reveal_data_cb (void *cls, diff --git a/src/auditor/taler-helper-auditor-reserves.c b/src/auditor/taler-helper-auditor-reserves.c index 610193187..e9cd51d8c 100644 --- a/src/auditor/taler-helper-auditor-reserves.c +++ b/src/auditor/taler-helper-auditor-reserves.c @@ -508,12 +508,7 @@ handle_reserve_out (void *cls, struct GNUNET_TIME_Timestamp valid_start; struct GNUNET_TIME_Timestamp expire_withdraw; enum GNUNET_DB_QueryStatus qs; - struct TALER_WithdrawRequestPS wsrd = { - .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW), - .purpose.size = htonl (sizeof (wsrd)), - .reserve_pub = *reserve_pub, - .h_coin_envelope = *h_blind_ev - }; + struct TALER_DenominationHash h_denom_pub; /* should be monotonically increasing */ GNUNET_assert (rowid >= ppr.last_reserve_out_serial_id); @@ -523,7 +518,7 @@ handle_reserve_out (void *cls, initializes wsrd.h_denomination_pub! */ qs = TALER_ARL_get_denomination_info (denom_pub, &issue, - &wsrd.h_denomination_pub); + &h_denom_pub); if (0 > qs) { GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs); @@ -569,17 +564,16 @@ handle_reserve_out (void *cls, GNUNET_JSON_pack_data_auto ("reserve_pub", reserve_pub), GNUNET_JSON_pack_data_auto ("denompub_h", - &wsrd.h_denomination_pub))); + &h_denom_pub))); } /* check reserve_sig (first: setup remaining members of wsrd) */ - TALER_amount_hton (&wsrd.amount_with_fee, - amount_with_fee); if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW, - &wsrd, - &reserve_sig->eddsa_signature, - &reserve_pub->eddsa_pub)) + TALER_wallet_withdraw_verify (&h_denom_pub, + amount_with_fee, + h_blind_ev, + reserve_pub, + reserve_sig)) { TALER_ARL_report (report_bad_sig_losses, GNUNET_JSON_PACK ( diff --git a/src/auditordb/auditordb_plugin.c b/src/auditordb/auditordb_plugin.c index d04e8815a..635247aa3 100644 --- a/src/auditordb/auditordb_plugin.c +++ b/src/auditordb/auditordb_plugin.c @@ -24,12 +24,6 @@ #include -/** - * Initialize the plugin. - * - * @param cfg configuration to use - * @return #GNUNET_OK on success - */ struct TALER_AUDITORDB_Plugin * TALER_AUDITORDB_plugin_load (const struct GNUNET_CONFIGURATION_Handle *cfg) { @@ -62,11 +56,6 @@ TALER_AUDITORDB_plugin_load (const struct GNUNET_CONFIGURATION_Handle *cfg) } -/** - * Shutdown the plugin. - * - * @param plugin the plugin to unload - */ void TALER_AUDITORDB_plugin_unload (struct TALER_AUDITORDB_Plugin *plugin) { diff --git a/src/auditordb/plugin_auditordb_postgres.c b/src/auditordb/plugin_auditordb_postgres.c index e0355d93b..ef5f0073d 100644 --- a/src/auditordb/plugin_auditordb_postgres.c +++ b/src/auditordb/plugin_auditordb_postgres.c @@ -144,7 +144,7 @@ postgres_create_tables (void *cls) * @param[in,out] pg the plugin-specific state * @return #GNUNET_OK on success */ -static int +static enum GNUNET_GenericReturnValue setup_connection (struct PostgresClosure *pg) { struct GNUNET_PQ_PreparedStatement ps[] = { diff --git a/src/bank-lib/bank_api_transfer.c b/src/bank-lib/bank_api_transfer.c index bbfc9cec8..3b50018d3 100644 --- a/src/bank-lib/bank_api_transfer.c +++ b/src/bank-lib/bank_api_transfer.c @@ -65,18 +65,7 @@ struct WirePackP GNUNET_NETWORK_STRUCT_END -/** - * Prepare for execution of a wire transfer from the exchange to some - * merchant. - * - * @param destination_account_payto_uri payto:// URL identifying where to send the money - * @param amount amount to transfer, already rounded - * @param exchange_base_url base URL of this exchange (included in subject - * to facilitate use of tracking API by merchant backend) - * @param wtid wire transfer identifier to use - * @param[out] buf set to transfer data to persist, NULL on error - * @param[out] buf_size set to number of bytes in @a buf, 0 on error - */ + void TALER_BANK_prepare_transfer ( const char *destination_account_payto_uri, @@ -247,17 +236,6 @@ handle_transfer_finished (void *cls, } -/** - * Execute a wire transfer. - * - * @param ctx curl context for our event loop - * @param auth authentication data to authenticate with the bank - * @param buf buffer with the prepared execution details - * @param buf_size number of bytes in @a buf - * @param cc function to call upon success - * @param cc_cls closure for @a cc - * @return NULL on error - */ struct TALER_BANK_TransferHandle * TALER_BANK_transfer ( struct GNUNET_CURL_Context *ctx, @@ -366,21 +344,6 @@ TALER_BANK_transfer ( } -/** - * Abort execution of a wire transfer. For example, because we are shutting - * down. Note that if an execution is aborted, it may or may not still - * succeed. - * - * The caller MUST run #TALER_BANK_transfer() again for the same request as - * soon as possible, to ensure that the request either ultimately succeeds or - * ultimately fails. Until this has been done, the transaction is in limbo - * (i.e. may or may not have been committed). - * - * This function cannot be used on a request handle if a response is already - * served for it. - * - * @param th the wire transfer request handle - */ void TALER_BANK_transfer_cancel (struct TALER_BANK_TransferHandle *th) { diff --git a/src/bank-lib/fakebank.c b/src/bank-lib/fakebank.c index 11993e558..ab1d73b4a 100644 --- a/src/bank-lib/fakebank.c +++ b/src/bank-lib/fakebank.c @@ -1386,19 +1386,19 @@ handle_admin_add_incoming (struct TALER_FAKEBANK_Handle *h, &json); switch (pr) { - case GNUNET_JSON_PR_OUT_OF_MEMORY: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_CONTINUE: - return MHD_YES; - case GNUNET_JSON_PR_REQUEST_TOO_LARGE: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_JSON_INVALID: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_SUCCESS: - break; + case GNUNET_JSON_PR_OUT_OF_MEMORY: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_CONTINUE: + return MHD_YES; + case GNUNET_JSON_PR_REQUEST_TOO_LARGE: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_JSON_INVALID: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_SUCCESS: + break; } { const char *debit_account; @@ -1510,19 +1510,19 @@ handle_transfer (struct TALER_FAKEBANK_Handle *h, &json); switch (pr) { - case GNUNET_JSON_PR_OUT_OF_MEMORY: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_CONTINUE: - return MHD_YES; - case GNUNET_JSON_PR_REQUEST_TOO_LARGE: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_JSON_INVALID: - GNUNET_break (0); - return MHD_NO; - case GNUNET_JSON_PR_SUCCESS: - break; + case GNUNET_JSON_PR_OUT_OF_MEMORY: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_CONTINUE: + return MHD_YES; + case GNUNET_JSON_PR_REQUEST_TOO_LARGE: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_JSON_INVALID: + GNUNET_break (0); + return MHD_NO; + case GNUNET_JSON_PR_SUCCESS: + break; } { struct GNUNET_HashCode uuid; diff --git a/src/benchmark/bank-benchmark-cs.conf b/src/benchmark/bank-benchmark-cs.conf new file mode 100644 index 000000000..d012f0faa --- /dev/null +++ b/src/benchmark/bank-benchmark-cs.conf @@ -0,0 +1,128 @@ +# This file is in the public domain. +# +[paths] +# Persistent data storage for the testcase +# This value is a default for `taler_config_home' +taler_test_home = exchange_benchmark_home/ + +[taler] +# Currency supported by the exchange (can only be one) +currency = EUR +CURRENCY_ROUND_UNIT = EUR:0.01 + +[exchange] +# how long is one signkey valid? +signkey_duration = 4 weeks +signkey_legal_duration = 2 years +# how long do we provide to clients denomination and signing keys +# ahead of time? +# Keep it short so the test runs fast. +lookahead_sign = 12h +# HTTP port the exchange listens to +port = 8081 +# Master public key used to sign the exchange's various keys +master_public_key = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG +# How to access our database +DB = postgres +# Base URL of the exchange. Must be set to a URL where the +# exchange (or the twister) is actually listening. +base_url = "http://localhost:8081/" + +WIREWATCH_IDLE_SLEEP_INTERVAL = 1500 ms + +[exchange-offline] +MASTER_PRIV_FILE = ${TALER_DATA_HOME}/exchange/offline-keys/master.priv + +[auditor] +BASE_URL = "http://localhost:8083/" + +[exchangedb-postgres] +config = "postgres:///talercheck" + +[benchmark-remote-exchange] +host = localhost +# Adjust $HOME to match remote target! +dir = $HOME/repos/taler/exchange/src/benchmark + +[bank] +HTTP_PORT = 8082 +SERVE = http +MAX_DEBT = EUR:100000000000.0 +MAX_DEBT_BANK = EUR:1000000000000000.0 + +[benchmark] +USER_PAYTO_URI = payto://x-taler-bank/localhost:8082/42 + +[exchange-account-2] +# What is the payto://-URL of the exchange (to generate wire response) +PAYTO_URI = "payto://x-taler-bank/localhost:8082/Exchange" +enable_debit = YES +enable_credit = YES + +[exchange-accountcredentials-2] +# What is the bank account (with the "Taler Bank" demo system)? Must end with "/". +WIRE_GATEWAY_URL = http://localhost:8082/Exchange/ +# Authentication information for basic authentication +WIRE_GATEWAY_AUTH_METHOD = "basic" +username = Exchange +password = x + + + + +# Sections starting with "coin_" specify which denominations +# the exchange should support (and their respective fee structure) +[coin_eur_ct_1] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_5] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_10] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/benchmark/bank-benchmark.conf b/src/benchmark/bank-benchmark-rsa.conf similarity index 97% rename from src/benchmark/bank-benchmark.conf rename to src/benchmark/bank-benchmark-rsa.conf index 1942d551b..f2f4dee50 100644 --- a/src/benchmark/bank-benchmark.conf +++ b/src/benchmark/bank-benchmark-rsa.conf @@ -81,6 +81,7 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_ct_10] @@ -92,6 +93,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_1] @@ -103,6 +105,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_5] @@ -114,6 +117,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_10] @@ -125,4 +129,5 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 diff --git a/src/benchmark/benchmark-cs.conf b/src/benchmark/benchmark-cs.conf new file mode 100644 index 000000000..d0d14b8d9 --- /dev/null +++ b/src/benchmark/benchmark-cs.conf @@ -0,0 +1,126 @@ +# This file is in the public domain. +# +[paths] +# Persistent data storage for the testcase +# This value is a default for `taler_config_home' +TALER_TEST_HOME = exchange_benchmark_home/ + +[taler] +# Currency supported by the exchange (can only be one) +CURRENCY = EUR +CURRENCY_ROUND_UNIT = EUR:0.01 + +[exchange] + +SIGNKEY_LEGAL_DURATION = 2 years + +# HTTP port the exchange listens to +PORT = 8081 +# Master public key used to sign the exchange's various keys +MASTER_PUBLIC_KEY = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG +# How to access our database +DB = postgres +# Base URL of the exchange. Must be set to a URL where the +# exchange (or the twister) is actually listening. +BASE_URL = "http://localhost:8081/" + +AGGREGATOR_SHARD_SIZE = 67108864 +#AGGREGATOR_SHARD_SIZE = 2147483648 + + + +WIREWATCH_IDLE_SLEEP_INTERVAL = 5 ms + +[exchange-offline] +MASTER_PRIV_FILE = ${TALER_DATA_HOME}/exchange/offline-keys/master.priv + +[auditor] +BASE_URL = "http://localhost:8083/" + +[exchangedb-postgres] +CONFIG = "postgres:///talercheck" + +[benchmark-remote-exchange] +HOST = localhost +# Adjust $HOME to match remote target! +DIR = $HOME/repos/taler/exchange/src/benchmark + +[bank] +HTTP_PORT = 8082 +SERVE = http +MAX_DEBT = EUR:100000000000.0 +MAX_DEBT_BANK = EUR:1000000000000000.0 + +[benchmark] +USER_PAYTO_URI = payto://x-taler-bank/localhost:8082/42 + +[exchange-account-test] +# What is the bank account (with the "Taler Bank" demo system)? Must end with "/". +PAYTO_URI = "payto://x-taler-bank/localhost/Exchange" +# Authentication information for basic authentication +ENABLE_DEBIT = YES +ENABLE_CREDIT = YES + +[exchange-accountcredentials-test] +WIRE_GATEWAY_URL = http://localhost:8082/Exchange/ +WIRE_GATEWAY_AUTH_METHOD = "basic" +USERNAME = Exchange +PASSWORD = x + + +# Sections starting with "coin_" specify which denominations +# the exchange should support (and their respective fee structure) +[coin_eur_ct_1] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_5] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_10] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/benchmark/benchmark.conf b/src/benchmark/benchmark-rsa.conf similarity index 97% rename from src/benchmark/benchmark.conf rename to src/benchmark/benchmark-rsa.conf index 5199ee872..7b5b0d1f1 100644 --- a/src/benchmark/benchmark.conf +++ b/src/benchmark/benchmark-rsa.conf @@ -79,6 +79,7 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_ct_10] @@ -90,6 +91,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_1] @@ -101,6 +103,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_5] @@ -112,6 +115,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 [coin_eur_10] @@ -123,4 +127,5 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 2048 diff --git a/src/benchmark/taler-aggregator-benchmark.c b/src/benchmark/taler-aggregator-benchmark.c index 365ae68dd..6452d6fca 100644 --- a/src/benchmark/taler-aggregator-benchmark.c +++ b/src/benchmark/taler-aggregator-benchmark.c @@ -228,7 +228,7 @@ struct Merchant /** * Salt used when computing @e h_wire. */ - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; /** * Account information for the merchant. @@ -490,8 +490,10 @@ run (void *cls, struct TALER_CoinPubHash c_hash; struct TALER_PlanchetDetail pd; struct TALER_BlindedDenominationSignature bds; - union TALER_DenominationBlindingKeyP bks; + struct TALER_PlanchetMasterSecretP ps; + struct TALER_ExchangeWithdrawValues alg_values; struct TALER_CoinSpendPublicKeyP coin_pub; + union TALER_DenominationBlindingKeyP bks; RANDOMIZE (&coin_pub); GNUNET_assert (GNUNET_OK == @@ -499,6 +501,7 @@ run (void *cls, &denom_pub, TALER_DENOMINATION_RSA, 1024)); + alg_values.cipher = TALER_DENOMINATION_RSA; TALER_denom_pub_hash (&denom_pub, &h_denom_pub); make_amountN (2, 0, &issue.properties.value); @@ -518,25 +521,29 @@ run (void *cls, return; } - TALER_blinding_secret_create (&bks); + + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); GNUNET_assert (GNUNET_OK == TALER_denom_blind (&denom_pub, &bks, NULL, /* FIXME-oec */ &coin_pub, + &alg_values, &c_hash, - &pd.coin_ev, - &pd.coin_ev_size)); + &pd.blinded_planchet)); GNUNET_assert (GNUNET_OK == TALER_denom_sign_blinded (&bds, &pk, - pd.coin_ev, - pd.coin_ev_size)); - GNUNET_free (pd.coin_ev); + &pd.blinded_planchet)); + TALER_blinded_planchet_free (&pd.blinded_planchet); GNUNET_assert (GNUNET_OK == TALER_denom_sig_unblind (&denom_sig, &bds, &bks, + &c_hash, + &alg_values, &denom_pub)); TALER_blinded_denom_sig_free (&bds); TALER_denom_pub_free (&denom_pub); diff --git a/src/exchange-tools/taler-crypto-worker.c b/src/exchange-tools/taler-crypto-worker.c index 6690b912b..34a153d4a 100644 --- a/src/exchange-tools/taler-crypto-worker.c +++ b/src/exchange-tools/taler-crypto-worker.c @@ -14,7 +14,7 @@ TALER; see the file COPYING. If not, see */ /** - * @file util/taler-crypto-worker.c + * @file exchange-tools/taler-crypto-worker.c * @brief Standalone process to perform various cryptographic operations. * @author Florian Dold */ @@ -178,6 +178,7 @@ run (void *cls, "sent response\n"); continue; } +#if FIXME_FLORIAN if (0 == strcmp ("setup_refresh_planchet", op)) { struct TALER_TransferSecretP transfer_secret; @@ -204,9 +205,9 @@ run (void *cls, global_ret = 1; return; } - TALER_planchet_setup_refresh (&transfer_secret, - coin_index, - &ps); + TALER_transfer_secret_to_planchet_secret (&transfer_secret, + coin_index, + &ps); GNUNET_CRYPTO_eddsa_key_get_public (&ps.coin_priv.eddsa_priv, &coin_pub.eddsa_pub); @@ -222,6 +223,7 @@ run (void *cls, "sent response\n"); continue; } +#endif GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "unsupported operation '%s'\n", op); diff --git a/src/exchange-tools/taler-exchange-offline.c b/src/exchange-tools/taler-exchange-offline.c index b7be2ddaa..55720a1b7 100644 --- a/src/exchange-tools/taler-exchange-offline.c +++ b/src/exchange-tools/taler-exchange-offline.c @@ -2530,16 +2530,16 @@ do_download (char *const *args) * Check that the security module keys are the same as before. If we had no * keys in store before, remember them (Trust On First Use). * - * @param secm security module keys, must be an array of length 2 + * @param secmset security module keys * @return #GNUNET_OK if keys match with what we have in store * #GNUNET_NO if we had nothing in store but now do * #GNUNET_SYSERR if keys changed from what we remember or other error */ -static int -tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) +static enum GNUNET_GenericReturnValue +tofu_check (const struct TALER_SecurityModulePublicKeySetP *secmset) { char *fn; - struct TALER_SecurityModulePublicKeyP old[2]; + struct TALER_SecurityModulePublicKeySetP oldset; ssize_t ret; if (GNUNET_OK != @@ -2557,11 +2557,11 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) GNUNET_DISK_file_test (fn)) { ret = GNUNET_DISK_fn_read (fn, - &old, - sizeof (old)); + &oldset, + sizeof (oldset)); if (GNUNET_SYSERR != ret) { - if (ret != sizeof (old)) + if (ret != sizeof (oldset)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "File `%s' corrupt\n", @@ -2570,9 +2570,9 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) return GNUNET_SYSERR; } /* TOFU check */ - if (0 != memcmp (old, - secm, - sizeof (old))) + if (0 != memcmp (&oldset, + secmset, + sizeof (*secmset))) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Fatal: security module keys changed (file `%s')!\n", @@ -2608,15 +2608,17 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) "SECM_ESIGN_PUBKEY", "key malformed"); GNUNET_free (key); + GNUNET_free (fn); return GNUNET_SYSERR; } GNUNET_free (key); if (0 != GNUNET_memcmp (&k, - &secm[1])) + &secmset->eddsa)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ESIGN security module key does not match SECM_ESIGN_PUBKEY in configuration\n"); + GNUNET_free (fn); return GNUNET_SYSERR; } } @@ -2639,15 +2641,50 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) "SECM_DENOM_PUBKEY", "key malformed"); GNUNET_free (key); + GNUNET_free (fn); return GNUNET_SYSERR; } GNUNET_free (key); if (0 != GNUNET_memcmp (&k, - &secm[0])) + &secmset->rsa)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DENOM security module key does not match SECM_DENOM_PUBKEY in configuration\n"); + GNUNET_free (fn); + return GNUNET_SYSERR; + } + } + if (GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string (kcfg, + "exchange-offline", + "SECM_DENOM_CS_PUBKEY", + &key)) + { + struct TALER_SecurityModulePublicKeyP k; + + if (GNUNET_OK != + GNUNET_STRINGS_string_to_data (key, + strlen (key), + &k, + sizeof (k))) + { + GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, + "exchange-offline", + "SECM_DENOM_CS_PUBKEY", + "key malformed"); + GNUNET_free (key); + GNUNET_free (fn); + return GNUNET_SYSERR; + } + GNUNET_free (key); + if (0 != + GNUNET_memcmp (&k, + &secmset->cs)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "DENOM security module key does not match SECM_DENOM_CS_PUBKEY in configuration\n"); + GNUNET_free (fn); return GNUNET_SYSERR; } } @@ -2664,8 +2701,8 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) /* persist keys for future runs */ if (GNUNET_OK != GNUNET_DISK_fn_write (fn, - secm, - sizeof (old), + secmset, + sizeof (oldset), GNUNET_DISK_PERM_USER_READ)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, @@ -2674,6 +2711,7 @@ tofu_check (const struct TALER_SecurityModulePublicKeyP secm[2]) GNUNET_free (fn); return GNUNET_SYSERR; } + GNUNET_free (fn); return GNUNET_NO; } @@ -2770,12 +2808,14 @@ show_signkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, /** * Output @a denomkeys for human consumption. * - * @param secm_pub security module public key used to sign the denominations + * @param secm_pub_rsa security module public key used to sign the RSA denominations + * @param secm_pub_cs security module public key used to sign the CS denominations * @param denomkeys keys to output * @return #GNUNET_OK on success */ -static int -show_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, +static enum GNUNET_GenericReturnValue +show_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub_rsa, + const struct TALER_SecurityModulePublicKeyP *secm_pub_cs, const json_t *denomkeys) { size_t index; @@ -2868,10 +2908,24 @@ show_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, section_name, stamp_start, duration, - secm_pub, + secm_pub_rsa, &secm_sig); } break; + case TALER_DENOMINATION_CS: + { + struct TALER_CsPubHashP h_cs; + + TALER_cs_pub_hash (&denom_pub.details.cs_public_key, + &h_cs); + ok = TALER_exchange_secmod_cs_verify (&h_cs, + section_name, + stamp_start, + duration, + secm_pub_cs, + &secm_sig); + } + break; default: GNUNET_break (0); ok = GNUNET_SYSERR; @@ -3023,7 +3077,7 @@ do_show (char *const *args) json_t *denomkeys; json_t *signkeys; struct TALER_MasterPublicKeyP mpub; - struct TALER_SecurityModulePublicKeyP secm[2]; + struct TALER_SecurityModulePublicKeySetP secmset; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_json ("future_denoms", &denomkeys), @@ -3032,9 +3086,11 @@ do_show (char *const *args) GNUNET_JSON_spec_fixed_auto ("master_pub", &mpub), GNUNET_JSON_spec_fixed_auto ("denom_secmod_public_key", - &secm[0]), + &secmset.rsa), + GNUNET_JSON_spec_fixed_auto ("denom_secmod_cs_public_key", + &secmset.cs), GNUNET_JSON_spec_fixed_auto ("signkey_secmod_public_key", - &secm[1]), + &secmset.eddsa), GNUNET_JSON_spec_end () }; @@ -3076,7 +3132,7 @@ do_show (char *const *args) return; } if (GNUNET_SYSERR == - tofu_check (secm)) + tofu_check (&secmset)) { global_ret = EXIT_FAILURE; test_shutdown (); @@ -3085,10 +3141,11 @@ do_show (char *const *args) return; } if ( (GNUNET_OK != - show_signkeys (&secm[1], + show_signkeys (&secmset.eddsa, signkeys)) || (GNUNET_OK != - show_denomkeys (&secm[0], + show_denomkeys (&secmset.rsa, + &secmset.cs, denomkeys)) ) { global_ret = EXIT_FAILURE; @@ -3111,7 +3168,7 @@ do_show (char *const *args) * @param[in,out] result array where to output the signatures * @return #GNUNET_OK on success */ -static int +static enum GNUNET_GenericReturnValue sign_signkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, const json_t *signkeys, json_t *result) @@ -3242,13 +3299,15 @@ load_age_mask (const char*section_name) /** * Sign @a denomkeys with offline key. * - * @param secm_pub security module public key used to sign the denominations + * @param secm_pub_rsa security module public key used to sign the RSA denominations + * @param secm_pub_cs security module public key used to sign the CS denominations * @param denomkeys keys to output * @param[in,out] result array where to output the signatures * @return #GNUNET_OK on success */ static enum GNUNET_GenericReturnValue -sign_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, +sign_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub_rsa, + const struct TALER_SecurityModulePublicKeyP *secm_pub_cs, const json_t *denomkeys, json_t *result) { @@ -3346,7 +3405,7 @@ sign_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, section_name, stamp_start, duration, - secm_pub, + secm_pub_rsa, &secm_sig)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, @@ -3359,6 +3418,30 @@ sign_denomkeys (const struct TALER_SecurityModulePublicKeyP *secm_pub, } } break; + case TALER_DENOMINATION_CS: + { + struct TALER_CsPubHashP h_cs; + + TALER_cs_pub_hash (&denom_pub.details.cs_public_key, + &h_cs); + if (GNUNET_OK != + TALER_exchange_secmod_cs_verify (&h_cs, + section_name, + stamp_start, + duration, + secm_pub_cs, + &secm_sig)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Invalid security module signature for denomination key %s (aborting)\n", + GNUNET_h2s (&h_denom_pub.hash)); + global_ret = EXIT_FAILURE; + test_shutdown (); + GNUNET_JSON_parse_free (spec); + return GNUNET_SYSERR; + } + } + break; default: global_ret = EXIT_FAILURE; test_shutdown (); @@ -3410,7 +3493,7 @@ do_sign (char *const *args) json_t *denomkeys; json_t *signkeys; struct TALER_MasterPublicKeyP mpub; - struct TALER_SecurityModulePublicKeyP secm[2]; + struct TALER_SecurityModulePublicKeySetP secmset; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_json ("future_denoms", &denomkeys), @@ -3419,9 +3502,11 @@ do_sign (char *const *args) GNUNET_JSON_spec_fixed_auto ("master_pub", &mpub), GNUNET_JSON_spec_fixed_auto ("denom_secmod_public_key", - &secm[0]), + &secmset.rsa), + GNUNET_JSON_spec_fixed_auto ("denom_secmod_cs_public_key", + &secmset.cs), GNUNET_JSON_spec_fixed_auto ("signkey_secmod_public_key", - &secm[1]), + &secmset.eddsa), GNUNET_JSON_spec_end () }; @@ -3465,7 +3550,7 @@ do_sign (char *const *args) return; } if (GNUNET_SYSERR == - tofu_check (secm)) + tofu_check (&secmset)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Fatal: security module keys changed!\n"); @@ -3482,11 +3567,12 @@ do_sign (char *const *args) GNUNET_assert (NULL != signkey_sig_array); GNUNET_assert (NULL != denomkey_sig_array); if ( (GNUNET_OK != - sign_signkeys (&secm[1], + sign_signkeys (&secmset.eddsa, signkeys, signkey_sig_array)) || (GNUNET_OK != - sign_denomkeys (&secm[0], + sign_denomkeys (&secmset.rsa, + &secmset.cs, denomkeys, denomkey_sig_array)) ) { diff --git a/src/exchange/Makefile.am b/src/exchange/Makefile.am index 44487a3a7..e4526f1c7 100644 --- a/src/exchange/Makefile.am +++ b/src/exchange/Makefile.am @@ -79,6 +79,7 @@ taler_exchange_transfer_LDADD = \ taler_exchange_httpd_SOURCES = \ taler-exchange-httpd.c taler-exchange-httpd.h \ taler-exchange-httpd_auditors.c taler-exchange-httpd_auditors.h \ + taler-exchange-httpd_csr.c taler-exchange-httpd_csr \ taler-exchange-httpd_db.c taler-exchange-httpd_db.h \ taler-exchange-httpd_deposit.c taler-exchange-httpd_deposit.h \ taler-exchange-httpd_deposits_get.c taler-exchange-httpd_deposits_get.h \ diff --git a/src/exchange/taler-exchange-aggregator.c b/src/exchange/taler-exchange-aggregator.c index 32b069f90..a2e87e2bf 100644 --- a/src/exchange/taler-exchange-aggregator.c +++ b/src/exchange/taler-exchange-aggregator.c @@ -199,7 +199,7 @@ static int test_mode; * Main work function that queries the DB and aggregates transactions * into larger wire transfers. * - * @param cls NULL + * @param cls a `struct Shard *` */ static void run_aggregation (void *cls); @@ -679,12 +679,6 @@ release_shard (struct Shard *s) } -/** - * Main work function that queries the DB and aggregates transactions - * into larger wire transfers. - * - * @param cls a `struct Shard *` - */ static void run_aggregation (void *cls) { diff --git a/src/exchange/taler-exchange-httpd.c b/src/exchange/taler-exchange-httpd.c index 52224655f..a0d0aa3b6 100644 --- a/src/exchange/taler-exchange-httpd.c +++ b/src/exchange/taler-exchange-httpd.c @@ -30,6 +30,7 @@ #include #include "taler_mhd_lib.h" #include "taler-exchange-httpd_auditors.h" +#include "taler-exchange-httpd_csr.h" #include "taler-exchange-httpd_deposit.h" #include "taler-exchange-httpd_deposits_get.h" #include "taler-exchange-httpd_extensions.h" @@ -193,7 +194,7 @@ static unsigned long long req_max; struct GNUNET_CURL_Context *TEH_curl_ctx; /** - * Context for integrating #exchange_curl_ctx with the + * Context for integrating #TEH_curl_ctx with the * GNUnet event loop. */ static struct GNUNET_CURL_RescheduleContext *exchange_curl_rc; @@ -522,8 +523,8 @@ proceed_with_handler (struct TEH_RequestContext *rc, sizeof (emsg), "Got %u/%u segments for %s request ('%s')", (NULL == args[i - 1]) - ? i - 1 - : i + ((NULL != fin) ? 1 : 0), + ? i - 1 + : i + ((NULL != fin) ? 1 : 0), rh->nargs, rh->url, url); @@ -922,6 +923,13 @@ handle_mhd_request (void *cls, .method = MHD_HTTP_METHOD_GET, .handler.get = &TEH_handler_wire }, + /* request R, used in clause schnorr withdraw and refresh */ + { + .url = "csr", + .method = MHD_HTTP_METHOD_POST, + .handler.post = &TEH_handler_csr, + .nargs = 0 + }, /* Withdrawing coins / interaction with reserves */ { .url = "reserves", @@ -1954,8 +1962,8 @@ run (void *cls, MHD_OPTION_CONNECTION_TIMEOUT, connection_timeout, (0 == allow_address_reuse) - ? MHD_OPTION_END - : MHD_OPTION_LISTENING_ADDRESS_REUSE, + ? MHD_OPTION_END + : MHD_OPTION_LISTENING_ADDRESS_REUSE, (unsigned int) allow_address_reuse, MHD_OPTION_END); if (NULL == mhd) diff --git a/src/exchange/taler-exchange-httpd_csr.c b/src/exchange/taler-exchange-httpd_csr.c new file mode 100644 index 000000000..47694d30b --- /dev/null +++ b/src/exchange/taler-exchange-httpd_csr.c @@ -0,0 +1,210 @@ +/* + This file is part of TALER + Copyright (C) 2014-2021 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation; either version 3, + or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty + of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General + Public License along with TALER; see the file COPYING. If not, + see +*/ +/** + * @file taler-exchange-httpd_csr.c + * @brief Handle /csr requests + * @author Lucien Heuzeveldt + * @author Gian Demarmles + */ +#include "platform.h" +#include +#include +#include "taler_json_lib.h" +#include "taler_mhd_lib.h" +#include "taler-exchange-httpd_csr.h" +#include "taler-exchange-httpd_responses.h" +#include "taler-exchange-httpd_keys.h" + + +MHD_RESULT +TEH_handler_csr (struct TEH_RequestContext *rc, + const json_t *root, + const char *const args[]) +{ + unsigned int csr_requests_num; + json_t *csr_requests; + json_t *csr_response_ewvs; + json_t *csr_response; + struct GNUNET_JSON_Specification spec[] = { + GNUNET_JSON_spec_json ("nks", + &csr_requests), + GNUNET_JSON_spec_end () + }; + enum TALER_ErrorCode ec; + struct TEH_DenominationKey *dk; + + (void) args; + + // parse input + { + enum GNUNET_GenericReturnValue res; + + res = TALER_MHD_parse_json_data (rc->connection, + root, + spec); + if (GNUNET_OK != res) + return (GNUNET_SYSERR == res) ? MHD_NO : MHD_YES; + } + csr_requests_num = json_array_size (csr_requests); + if (TALER_MAX_FRESH_COINS <= csr_requests_num) + { + GNUNET_JSON_parse_free (spec); + return TALER_MHD_reply_with_error ( + rc->connection, + MHD_HTTP_BAD_REQUEST, + TALER_EC_EXCHANGE_GENERIC_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE, + NULL); + } + struct TALER_CsNonce nonces[GNUNET_NZL (csr_requests_num)]; + struct TALER_DenominationHash denom_pub_hashes[GNUNET_NZL (csr_requests_num)]; + for (unsigned int i = 0; i < csr_requests_num; i++) + { + struct TALER_CsNonce *nonce = &nonces[i]; + struct TALER_DenominationHash *denom_pub_hash = &denom_pub_hashes[i]; + struct GNUNET_JSON_Specification csr_spec[] = { + GNUNET_JSON_spec_fixed ("nonce", + nonce, + sizeof (struct TALER_CsNonce)), + GNUNET_JSON_spec_fixed ("denom_pub_hash", + denom_pub_hash, + sizeof (struct TALER_DenominationHash)), + GNUNET_JSON_spec_end () + }; + enum GNUNET_GenericReturnValue res; + + res = TALER_MHD_parse_json_array (rc->connection, + csr_requests, + csr_spec, + i, + -1); + if (GNUNET_OK != res) + { + GNUNET_JSON_parse_free (spec); + return (GNUNET_NO == res) ? MHD_YES : MHD_NO; + } + } + GNUNET_JSON_parse_free (spec); + + struct TALER_ExchangeWithdrawValues ewvs[GNUNET_NZL (csr_requests_num)]; + for (unsigned int i = 0; i < csr_requests_num; i++) + { + const struct TALER_CsNonce *nonce = &nonces[i]; + const struct TALER_DenominationHash *denom_pub_hash = &denom_pub_hashes[i]; + struct TALER_DenominationCSPublicRPairP *r_pub + = &ewvs[i].details.cs_values; + + ewvs[i].cipher = TALER_DENOMINATION_CS; + // check denomination referenced by denom_pub_hash + { + struct TEH_KeyStateHandle *ksh; + + ksh = TEH_keys_get_state (); + if (NULL == ksh) + { + return TALER_MHD_reply_with_error (rc->connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + TALER_EC_EXCHANGE_GENERIC_KEYS_MISSING, + NULL); + } + dk = TEH_keys_denomination_by_hash2 (ksh, + denom_pub_hash, + NULL, + NULL); + if (NULL == dk) + { + return TEH_RESPONSE_reply_unknown_denom_pub_hash ( + rc->connection, + &denom_pub_hash[i]); + } + if (GNUNET_TIME_absolute_is_past (dk->meta.expire_withdraw.abs_time)) + { + /* This denomination is past the expiration time for withdraws/refreshes*/ + return TEH_RESPONSE_reply_expired_denom_pub_hash ( + rc->connection, + denom_pub_hash, + TALER_EC_EXCHANGE_GENERIC_DENOMINATION_EXPIRED, + "CSR"); + } + if (GNUNET_TIME_absolute_is_future (dk->meta.start.abs_time)) + { + /* This denomination is not yet valid, no need to check + for idempotency! */ + return TEH_RESPONSE_reply_expired_denom_pub_hash ( + rc->connection, + denom_pub_hash, + TALER_EC_EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE, + "CSR"); + } + if (dk->recoup_possible) + { + /* This denomination has been revoked */ + return TEH_RESPONSE_reply_expired_denom_pub_hash ( + rc->connection, + denom_pub_hash, + TALER_EC_EXCHANGE_GENERIC_DENOMINATION_REVOKED, + "CSR"); + } + if (TALER_DENOMINATION_CS != dk->denom_pub.cipher) + { + // denomination is valid but not CS + return TEH_RESPONSE_reply_invalid_denom_cipher_for_operation ( + rc->connection, + denom_pub_hash); + } + } + + // derive r_pub + // FIXME: bundle all requests into one derivation request (TEH_keys_..., crypto helper, security module) + ec = TEH_keys_denomination_cs_r_pub (denom_pub_hash, + nonce, + r_pub); + if (TALER_EC_NONE != ec) + { + GNUNET_break (0); + return TALER_MHD_reply_with_ec (rc->connection, + ec, + NULL); + } + } + + // send response + csr_response_ewvs = json_array (); + for (unsigned int i = 0; i < csr_requests_num; i++) + { + json_t *csr_obj; + + csr_obj = GNUNET_JSON_PACK ( + TALER_JSON_pack_exchange_withdraw_values ("ewv", + &ewvs[i])); + GNUNET_assert (NULL != csr_obj); + GNUNET_assert (0 == + json_array_append_new (csr_response_ewvs, + csr_obj)); + } + csr_response = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_array_steal ("ewvs", + csr_response_ewvs)); + GNUNET_assert (NULL != csr_response); + return TALER_MHD_reply_json_steal (rc->connection, + csr_response, + MHD_HTTP_OK); +} + + +/* end of taler-exchange-httpd_csr.c */ diff --git a/src/exchange/taler-exchange-httpd_csr.h b/src/exchange/taler-exchange-httpd_csr.h new file mode 100644 index 000000000..3bd98742b --- /dev/null +++ b/src/exchange/taler-exchange-httpd_csr.h @@ -0,0 +1,43 @@ +/* + This file is part of TALER + Copyright (C) 2014-2021 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with + TALER; see the file COPYING. If not, see +*/ +/** + * @file taler-exchange-httpd_csr.h + * @brief Handle /csr requests + * @author Lucien Heuzeveldt + * @author Gian Demarmles + */ +#ifndef TALER_EXCHANGE_HTTPD_CSR_H +#define TALER_EXCHANGE_HTTPD_CSR_H + +#include +#include "taler-exchange-httpd.h" + + +/** + * Handle a "/csr" request. Parses the "nonce" and + * the "denom_pub_hash" (identifying a denomination) used to derive the r_pub. + * + * @param rc request context + * @param root uploaded JSON data + * @param args empty array + * @return MHD result code + */ +MHD_RESULT +TEH_handler_csr (struct TEH_RequestContext *rc, + const json_t *root, + const char *const args[]); + +#endif diff --git a/src/exchange/taler-exchange-httpd_deposit.c b/src/exchange/taler-exchange-httpd_deposit.c index c3efd9ff5..d750ec70e 100644 --- a/src/exchange/taler-exchange-httpd_deposit.c +++ b/src/exchange/taler-exchange-httpd_deposit.c @@ -51,6 +51,7 @@ * @param h_contract_terms hash of contract details * @param exchange_timestamp exchange's timestamp * @param refund_deadline until when this deposit be refunded + * @param wire_deadline until when will the exchange wire the funds * @param merchant merchant public key * @param amount_without_fee fraction of coin value to deposit, without the fee * @return MHD result code @@ -359,6 +360,15 @@ TEH_handler_deposit (struct MHD_Connection *connection, TALER_EC_EXCHANGE_GENERIC_DENOMINATION_REVOKED, "DEPOSIT"); } + if (dk->denom_pub.cipher != deposit.coin.denom_sig.cipher) + { + /* denomination cipher and denomination signature cipher not the same */ + GNUNET_JSON_parse_free (spec); + return TALER_MHD_reply_with_error (connection, + MHD_HTTP_BAD_REQUEST, + TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH, + NULL); + } deposit.deposit_fee = dk->meta.fee_deposit; /* check coin signature */ diff --git a/src/exchange/taler-exchange-httpd_keys.c b/src/exchange/taler-exchange-httpd_keys.c index 4a68ef56a..4b0acd852 100644 --- a/src/exchange/taler-exchange-httpd_keys.c +++ b/src/exchange/taler-exchange-httpd_keys.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2020, 2021 Taler Systems SA + Copyright (C) 2020-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -103,6 +103,11 @@ struct HelperDenomination */ struct TALER_RsaPubHashP h_rsa; + /** + * Hash of the CS key. + */ + struct TALER_CsPubHashP h_cs; + } h_details; /** @@ -188,7 +193,12 @@ struct HelperState /** * Handle for the denom/RSA helper. */ - struct TALER_CRYPTO_RsaDenominationHelper *dh; + struct TALER_CRYPTO_RsaDenominationHelper *rsadh; + + /** + * Handle for the denom/CS helper. + */ + struct TALER_CRYPTO_CsDenominationHelper *csdh; /** * Map from H(denom_pub) to `struct HelperDenomination` entries. @@ -200,6 +210,11 @@ struct HelperState */ struct GNUNET_CONTAINER_MultiHashMap *rsa_keys; + /** + * Map from H(cs_pub) to `struct HelperDenomination` entries. + */ + struct GNUNET_CONTAINER_MultiHashMap *cs_keys; + /** * Map from `struct TALER_ExchangePublicKey` to `struct HelperSignkey` * entries. Based on the fact that a `struct GNUNET_PeerIdentity` is also @@ -424,7 +439,12 @@ static struct GNUNET_TIME_Relative signkey_legal_duration; /** * RSA security module public key, all zero if not known. */ -static struct TALER_SecurityModulePublicKeyP denom_sm_pub; +static struct TALER_SecurityModulePublicKeyP denom_rsa_sm_pub; + +/** + * CS security module public key, all zero if not known. + */ +static struct TALER_SecurityModulePublicKeyP denom_cs_sm_pub; /** * EdDSA security module public key, all zero if not known. @@ -541,6 +561,7 @@ check_dk (void *cls, if (TALER_DENOMINATION_RSA == dk->denom_pub.cipher) GNUNET_assert (GNUNET_CRYPTO_rsa_public_key_check ( dk->denom_pub.details.rsa_public_key)); + // nothing to do for TALER_DENOMINATION_CS return GNUNET_OK; } @@ -609,19 +630,43 @@ clear_response_cache (struct TEH_KeyStateHandle *ksh) * @param sm_pub RSA security module public key to check */ static void -check_denom_sm_pub (const struct TALER_SecurityModulePublicKeyP *sm_pub) +check_denom_rsa_sm_pub (const struct TALER_SecurityModulePublicKeyP *sm_pub) { if (0 != GNUNET_memcmp (sm_pub, - &denom_sm_pub)) + &denom_rsa_sm_pub)) { - if (! GNUNET_is_zero (&denom_sm_pub)) + if (! GNUNET_is_zero (&denom_rsa_sm_pub)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Our RSA security module changed its key. This must not happen.\n"); GNUNET_assert (0); } - denom_sm_pub = *sm_pub; /* TOFU ;-) */ + denom_rsa_sm_pub = *sm_pub; /* TOFU ;-) */ + } +} + + +/** + * Check that the given CS security module's public key is the one + * we have pinned. If it does not match, we die hard. + * + * @param sm_pub RSA security module public key to check + */ +static void +check_denom_cs_sm_pub (const struct TALER_SecurityModulePublicKeyP *sm_pub) +{ + if (0 != + GNUNET_memcmp (sm_pub, + &denom_cs_sm_pub)) + { + if (! GNUNET_is_zero (&denom_cs_sm_pub)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Our CS security module changed its key. This must not happen.\n"); + GNUNET_assert (0); + } + denom_cs_sm_pub = *sm_pub; /* TOFU ;-) */ } } @@ -659,7 +704,7 @@ check_esign_sm_pub (const struct TALER_SecurityModulePublicKeyP *sm_pub) * @param value the `struct HelperDenomination` to release * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue free_denom_cb (void *cls, const struct GNUNET_HashCode *h_denom_pub, void *value) @@ -712,6 +757,8 @@ destroy_key_helpers (struct HelperState *hs) hs); GNUNET_CONTAINER_multihashmap_destroy (hs->rsa_keys); hs->rsa_keys = NULL; + GNUNET_CONTAINER_multihashmap_destroy (hs->cs_keys); + hs->cs_keys = NULL; GNUNET_CONTAINER_multihashmap_destroy (hs->denom_keys); hs->denom_keys = NULL; GNUNET_CONTAINER_multipeermap_iterate (hs->esign_keys, @@ -719,10 +766,15 @@ destroy_key_helpers (struct HelperState *hs) hs); GNUNET_CONTAINER_multipeermap_destroy (hs->esign_keys); hs->esign_keys = NULL; - if (NULL != hs->dh) + if (NULL != hs->rsadh) { - TALER_CRYPTO_helper_rsa_disconnect (hs->dh); - hs->dh = NULL; + TALER_CRYPTO_helper_rsa_disconnect (hs->rsadh); + hs->rsadh = NULL; + } + if (NULL != hs->csdh) + { + TALER_CRYPTO_helper_cs_disconnect (hs->csdh); + hs->csdh = NULL; } if (NULL != hs->esh) { @@ -743,7 +795,6 @@ static struct TALER_AgeMask load_age_mask (const char*section_name) { static const struct TALER_AgeMask null_mask = {0}; - enum GNUNET_GenericReturnValue ret; struct TALER_AgeMask age_mask = TALER_extensions_age_restriction_ageMask (); if (age_mask.mask == 0) @@ -753,20 +804,22 @@ load_age_mask (const char*section_name) TEH_cfg, section_name, "AGE_RESTRICTED"))) - return null_mask; + { + enum GNUNET_GenericReturnValue ret; - ret = GNUNET_CONFIGURATION_get_value_yesno (TEH_cfg, - section_name, - "AGE_RESTRICTED"); - if (GNUNET_YES == ret) - return age_mask; - - if (GNUNET_SYSERR == ret) - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - section_name, - "AGE_RESTRICTED", - "Value must be YES or NO\n"); - return null_mask; + if (GNUNET_SYSERR == + (ret = GNUNET_CONFIGURATION_get_value_yesno (TEH_cfg, + section_name, + "AGE_RESTRICTED"))) + { + GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, + section_name, + "AGE_RESTRICTED", + "Value must be YES or NO\n"); + return null_mask; + } + } + return age_mask; } @@ -782,7 +835,7 @@ load_age_mask (const char*section_name) * zero if the key has been revoked or purged * @param validity_duration how long does the key remain available for signing; * zero if the key has been revoked or purged - * @param h_denom_pub hash of the @a denom_pub that is available (or was purged) + * @param h_rsa hash of the @a denom_pub that is available (or was purged) * @param denom_pub the public key itself, NULL if the key was revoked or purged * @param sm_pub public key of the security module, NULL if the key was revoked or purged * @param sm_sig signature from the security module, NULL if the key was revoked or purged @@ -819,7 +872,7 @@ helper_rsa_cb ( return; } GNUNET_assert (NULL != sm_pub); - check_denom_sm_pub (sm_pub); + check_denom_rsa_sm_pub (sm_pub); hd = GNUNET_new (struct HelperDenomination); hd->start_time = start_time; hd->validity_duration = validity_duration; @@ -851,6 +904,86 @@ helper_rsa_cb ( } +/** + * Function called with information about available CS keys for signing. Usually + * only called once per key upon connect. Also called again in case a key is + * being revoked, in that case with an @a end_time of zero. + * + * @param cls closure with the `struct HelperState *` + * @param section_name name of the denomination type in the configuration; + * NULL if the key has been revoked or purged + * @param start_time when does the key become available for signing; + * zero if the key has been revoked or purged + * @param validity_duration how long does the key remain available for signing; + * zero if the key has been revoked or purged + * @param h_cs hash of the @a denom_pub that is available (or was purged) + * @param denom_pub the public key itself, NULL if the key was revoked or purged + * @param sm_pub public key of the security module, NULL if the key was revoked or purged + * @param sm_sig signature from the security module, NULL if the key was revoked or purged + * The signature was already verified against @a sm_pub. + */ +static void +helper_cs_cb ( + void *cls, + const char *section_name, + struct GNUNET_TIME_Timestamp start_time, + struct GNUNET_TIME_Relative validity_duration, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_DenominationPublicKey *denom_pub, + const struct TALER_SecurityModulePublicKeyP *sm_pub, + const struct TALER_SecurityModuleSignatureP *sm_sig) +{ + struct HelperState *hs = cls; + struct HelperDenomination *hd; + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "CS helper announces key %s for denomination type %s with validity %s\n", + GNUNET_h2s (&h_cs->hash), + section_name, + GNUNET_STRINGS_relative_time_to_string (validity_duration, + GNUNET_NO)); + key_generation++; + TEH_resume_keys_requests (false); + hd = GNUNET_CONTAINER_multihashmap_get (hs->cs_keys, + &h_cs->hash); + if (NULL != hd) + { + /* should be just an update (revocation!), so update existing entry */ + hd->validity_duration = validity_duration; + return; + } + GNUNET_assert (NULL != sm_pub); + check_denom_cs_sm_pub (sm_pub); + hd = GNUNET_new (struct HelperDenomination); + hd->start_time = start_time; + hd->validity_duration = validity_duration; + hd->h_details.h_cs = *h_cs; + hd->sm_sig = *sm_sig; + GNUNET_assert (TALER_DENOMINATION_CS == denom_pub->cipher); + TALER_denom_pub_deep_copy (&hd->denom_pub, + denom_pub); + /* load the age mask for the denomination, if applicable */ + hd->denom_pub.age_mask = load_age_mask (section_name); + TALER_denom_pub_hash (&hd->denom_pub, + &hd->h_denom_pub); + hd->section_name = GNUNET_strdup (section_name); + GNUNET_assert ( + GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put ( + hs->denom_keys, + &hd->h_denom_pub.hash, + hd, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert ( + GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put ( + hs->cs_keys, + &hd->h_details.h_cs.hash, + hd, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); +} + + /** * Function called with information about available keys for signing. Usually * only called once per key upon connect. Also called again in case a key is @@ -927,13 +1060,24 @@ setup_key_helpers (struct HelperState *hs) hs->rsa_keys = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES); + hs->cs_keys + = GNUNET_CONTAINER_multihashmap_create (1024, + GNUNET_YES); hs->esign_keys = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_NO /* MUST BE NO! */); - hs->dh = TALER_CRYPTO_helper_rsa_connect (TEH_cfg, - &helper_rsa_cb, - hs); - if (NULL == hs->dh) + hs->rsadh = TALER_CRYPTO_helper_rsa_connect (TEH_cfg, + &helper_rsa_cb, + hs); + if (NULL == hs->rsadh) + { + destroy_key_helpers (hs); + return GNUNET_SYSERR; + } + hs->csdh = TALER_CRYPTO_helper_cs_connect (TEH_cfg, + &helper_cs_cb, + hs); + if (NULL == hs->csdh) { destroy_key_helpers (hs); return GNUNET_SYSERR; @@ -958,7 +1102,8 @@ setup_key_helpers (struct HelperState *hs) static void sync_key_helpers (struct HelperState *hs) { - TALER_CRYPTO_helper_rsa_poll (hs->dh); + TALER_CRYPTO_helper_rsa_poll (hs->rsadh); + TALER_CRYPTO_helper_cs_poll (hs->csdh); TALER_CRYPTO_helper_esign_poll (hs->esh); } @@ -971,7 +1116,7 @@ sync_key_helpers (struct HelperState *hs) * @param value a `struct TEH_DenominationKey` to free * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue clear_denomination_cb (void *cls, const struct GNUNET_HashCode *h_denom_pub, void *value) @@ -1002,7 +1147,7 @@ clear_denomination_cb (void *cls, * @param value a `struct SigningKey` to free * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue clear_signkey_cb (void *cls, const struct GNUNET_PeerIdentity *pid, void *value) @@ -1244,7 +1389,7 @@ struct GetAuditorSigsContext * @param value a `struct TEH_DenominationKey` * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue get_auditor_sigs (void *cls, const struct GNUNET_HashCode *h_denom_pub, void *value) @@ -1377,7 +1522,7 @@ struct SignKeyCtx * @param value a `struct SigningKey` * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue add_sign_key_cb (void *cls, const struct GNUNET_PeerIdentity *pid, void *value) @@ -1446,7 +1591,7 @@ struct DenomKeyCtx * @param value a `struct TEH_DenominationKey` * @return #GNUNET_OK (continue to iterate) */ -static int +static enum GNUNET_GenericReturnValue add_denom_key_cb (void *cls, const struct GNUNET_HashCode *h_denom_pub, void *value) @@ -1760,6 +1905,10 @@ create_krd (struct TEH_KeyStateHandle *ksh, r = json_object_update (keys, sig); GNUNET_assert (0 == r); } + else + { + json_decref (extensions); + } // Special case for age restrictions: if enabled, provide the list of // age-restricted denominations. @@ -2286,44 +2435,73 @@ TEH_keys_denomination_by_hash2 ( } -struct TALER_BlindedDenominationSignature +enum TALER_ErrorCode TEH_keys_denomination_sign (const struct TALER_DenominationHash *h_denom_pub, - const void *msg, - size_t msg_size, - enum TALER_ErrorCode *ec) + const struct TALER_BlindedPlanchet *bp, + struct TALER_BlindedDenominationSignature *bs) +{ + struct TEH_KeyStateHandle *ksh; + struct HelperDenomination *hd; + + ksh = TEH_keys_get_state (); + if (NULL == ksh) + return TALER_EC_EXCHANGE_GENERIC_KEYS_MISSING; + hd = GNUNET_CONTAINER_multihashmap_get (ksh->helpers->denom_keys, + &h_denom_pub->hash); + if (NULL == hd) + return TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN; + if (bp->cipher != hd->denom_pub.cipher) + return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE; + switch (hd->denom_pub.cipher) + { + case TALER_DENOMINATION_RSA: + return TALER_CRYPTO_helper_rsa_sign ( + ksh->helpers->rsadh, + &hd->h_details.h_rsa, + bp->details.rsa_blinded_planchet.blinded_msg, + bp->details.rsa_blinded_planchet.blinded_msg_size, + bs); + case TALER_DENOMINATION_CS: + return TALER_CRYPTO_helper_cs_sign ( + ksh->helpers->csdh, + &hd->h_details.h_cs, + &bp->details.cs_blinded_planchet, + bs); + default: + return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE; + } +} + + +enum TALER_ErrorCode +TEH_keys_denomination_cs_r_pub (const struct + TALER_DenominationHash *h_denom_pub, + const struct TALER_CsNonce *nonce, + struct TALER_DenominationCSPublicRPairP *r_pub) { struct TEH_KeyStateHandle *ksh; - struct TALER_BlindedDenominationSignature none; struct HelperDenomination *hd; - memset (&none, - 0, - sizeof (none)); ksh = TEH_keys_get_state (); if (NULL == ksh) { - *ec = TALER_EC_EXCHANGE_GENERIC_KEYS_MISSING; - return none; + return TALER_EC_EXCHANGE_GENERIC_KEYS_MISSING; } hd = GNUNET_CONTAINER_multihashmap_get (ksh->helpers->denom_keys, &h_denom_pub->hash); if (NULL == hd) { - *ec = TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN; - return none; + return TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN; } - switch (hd->denom_pub.cipher) + if (TALER_DENOMINATION_CS != hd->denom_pub.cipher) { - case TALER_DENOMINATION_RSA: - return TALER_CRYPTO_helper_rsa_sign (ksh->helpers->dh, - &hd->h_details.h_rsa, - msg, - msg_size, - ec); - default: - *ec = TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE; - return none; + return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE; } + + return TALER_CRYPTO_helper_cs_r_derive (ksh->helpers->csdh, + &hd->h_details.h_cs, + nonce, + r_pub); } @@ -2349,10 +2527,15 @@ TEH_keys_denomination_revoke (const struct TALER_DenominationHash *h_denom_pub) switch (hd->denom_pub.cipher) { case TALER_DENOMINATION_RSA: - TALER_CRYPTO_helper_rsa_revoke (ksh->helpers->dh, + TALER_CRYPTO_helper_rsa_revoke (ksh->helpers->rsadh, &hd->h_details.h_rsa); TEH_keys_update_states (); return; + case TALER_DENOMINATION_CS: + TALER_CRYPTO_helper_cs_revoke (ksh->helpers->csdh, + &hd->h_details.h_cs); + TEH_keys_update_states (); + return; default: GNUNET_break (0); return; @@ -2948,7 +3131,8 @@ TEH_keys_management_get_keys_handler (const struct TEH_RequestHandler *rh, .signkeys = json_array () }; - if (GNUNET_is_zero (&denom_sm_pub)) + if ( (GNUNET_is_zero (&denom_rsa_sm_pub)) && + (GNUNET_is_zero (&denom_cs_sm_pub)) ) { return TALER_MHD_reply_with_error (connection, MHD_HTTP_BAD_GATEWAY, @@ -2979,7 +3163,9 @@ TEH_keys_management_get_keys_handler (const struct TEH_RequestHandler *rh, GNUNET_JSON_pack_data_auto ("master_pub", &TEH_master_public_key), GNUNET_JSON_pack_data_auto ("denom_secmod_public_key", - &denom_sm_pub), + &denom_rsa_sm_pub), + GNUNET_JSON_pack_data_auto ("denom_secmod_cs_public_key", + &denom_cs_sm_pub), GNUNET_JSON_pack_data_auto ("signkey_secmod_public_key", &esign_sm_pub)); GNUNET_log (GNUNET_ERROR_TYPE_INFO, diff --git a/src/exchange/taler-exchange-httpd_keys.h b/src/exchange/taler-exchange-httpd_keys.h index ce9068ec2..a329c4f12 100644 --- a/src/exchange/taler-exchange-httpd_keys.h +++ b/src/exchange/taler-exchange-httpd_keys.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2020 Taler Systems SA + Copyright (C) 2020-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -160,32 +160,46 @@ TEH_keys_denomination_by_hash (const struct TALER_DenominationHash *h_denom_pub, * or NULL if @a h_denom_pub could not be found */ struct TEH_DenominationKey * -TEH_keys_denomination_by_hash2 (struct TEH_KeyStateHandle *ksh, - const struct - TALER_DenominationHash *h_denom_pub, - struct MHD_Connection *conn, - MHD_RESULT *mret); +TEH_keys_denomination_by_hash2 ( + struct TEH_KeyStateHandle *ksh, + const struct TALER_DenominationHash *h_denom_pub, + struct MHD_Connection *conn, + MHD_RESULT *mret); + /** * Request to sign @a msg using the public key corresponding to * @a h_denom_pub. * * @param h_denom_pub hash of the public key to use to sign - * @param msg message to sign - * @param msg_size number of bytes in @a msg - * @param[out] ec set to the error code (or #TALER_EC_NONE on success) - * @return signature, the value inside the structure will be NULL on failure, - * see @a ec for details about the failure + * @param bp blinded planchet to sign + * @param[out] bs set to the blind signature on success + * @return #TALER_EC_NONE on success */ -struct TALER_BlindedDenominationSignature +enum TALER_ErrorCode TEH_keys_denomination_sign (const struct TALER_DenominationHash *h_denom_pub, - const void *msg, - size_t msg_size, - enum TALER_ErrorCode *ec); + const struct TALER_BlindedPlanchet *bp, + struct TALER_BlindedDenominationSignature *bs); /** - * Revoke the public key associated with @param h_denom_pub . + * Request to derive CS @a r_pub using the denomination corresponding to @a h_denom_pub + * and @a nonce. + * + * @param h_denom_pub hash of the public key to use to derive r_pub + * @param nonce withdraw/refresh nonce + * @param[out] r_pub where to write the result + * @return #TALER_EC_NONE on success + */ +enum TALER_ErrorCode +TEH_keys_denomination_cs_r_pub ( + const struct TALER_DenominationHash *h_denom_pub, + const struct TALER_CsNonce *nonce, + struct TALER_DenominationCSPublicRPairP *r_pub); + + +/** + * Revoke the public key associated with @a h_denom_pub. * This function should be called AFTER the database was * updated, as it also triggers #TEH_keys_update_states(). * diff --git a/src/exchange/taler-exchange-httpd_kyc-check.h b/src/exchange/taler-exchange-httpd_kyc-check.h index 52fe5f16b..b6434b601 100644 --- a/src/exchange/taler-exchange-httpd_kyc-check.h +++ b/src/exchange/taler-exchange-httpd_kyc-check.h @@ -29,7 +29,7 @@ * Handle a "/kyc-check" request. Checks the KYC * status of the given account and returns it. * - * @param connection request to handle + * @param rc details about the request to handle * @param args one argument with the payment_target_uuid * @return MHD result code */ diff --git a/src/exchange/taler-exchange-httpd_link.c b/src/exchange/taler-exchange-httpd_link.c index d3c0d6a5a..47b803ffa 100644 --- a/src/exchange/taler-exchange-httpd_link.c +++ b/src/exchange/taler-exchange-httpd_link.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2019 Taler Systems SA + Copyright (C) 2014-2019, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -86,8 +86,18 @@ handle_link_data (void *cls, &pos->denom_pub), TALER_JSON_pack_blinded_denom_sig ("ev_sig", &pos->ev_sig), + GNUNET_JSON_pack_uint64 ("coin_idx", + pos->coin_refresh_offset), + TALER_JSON_pack_exchange_withdraw_values ("ewv", + &pos->alg_values), GNUNET_JSON_pack_data_auto ("link_sig", - &pos->orig_coin_link_sig)); + &pos->orig_coin_link_sig), + GNUNET_JSON_pack_allow_null ( + pos->have_nonce + ? GNUNET_JSON_pack_data_auto ("cs_nonce", + &pos->nonce) + : GNUNET_JSON_pack_string ("cs_nonce", + NULL))); if ( (NULL == obj) || (0 != json_array_append_new (list, diff --git a/src/exchange/taler-exchange-httpd_melt.c b/src/exchange/taler-exchange-httpd_melt.c index 334ec1287..8bfdf8cef 100644 --- a/src/exchange/taler-exchange-httpd_melt.c +++ b/src/exchange/taler-exchange-httpd_melt.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -183,6 +183,7 @@ melt_transaction (void *cls, } if (! balance_ok) { + GNUNET_break_op (0); TEH_plugin->rollback (TEH_plugin->cls); *mhd_ret = TEH_RESPONSE_reply_coin_insufficient_funds ( @@ -302,6 +303,10 @@ check_melt_valid (struct MHD_Connection *connection, rmc->coin_refresh_fee = dk->meta.fee_refresh; rmc->coin_value = dk->meta.value; + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Melted coin's denomination is worth %s\n", + TALER_amount2s (&dk->meta.value)); + /* sanity-check that "total melt amount > melt fee" */ if (0 < TALER_amount_cmp (&rmc->coin_refresh_fee, diff --git a/src/exchange/taler-exchange-httpd_melt.h b/src/exchange/taler-exchange-httpd_melt.h index 0edaf2475..b15fd07c7 100644 --- a/src/exchange/taler-exchange-httpd_melt.h +++ b/src/exchange/taler-exchange-httpd_melt.h @@ -30,10 +30,10 @@ /** * Handle a "/coins/$COIN_PUB/melt" request. Parses the request into the JSON - * components and then hands things of to #check_for_denomination_key() to + * components and then hands things of to #check_melt_valid() to * validate the melted coins, the signature and execute the melt using - * handle_melt(). - + * melt_transaction(). + * * @param connection the MHD connection to handle * @param coin_pub public key of the coin * @param root uploaded JSON data diff --git a/src/exchange/taler-exchange-httpd_recoup-refresh.c b/src/exchange/taler-exchange-httpd_recoup-refresh.c index ec5589926..bbf6defee 100644 --- a/src/exchange/taler-exchange-httpd_recoup-refresh.c +++ b/src/exchange/taler-exchange-httpd_recoup-refresh.c @@ -162,6 +162,8 @@ recoup_refresh_transaction (void *cls, * * @param connection the MHD connection to handle * @param coin information about the coin + * @param exchange_vals values contributed by the exchange + * during refresh * @param coin_bks blinding data of the coin (to be checked) * @param coin_sig signature of the coin * @return MHD result code @@ -170,7 +172,9 @@ static MHD_RESULT verify_and_execute_recoup_refresh ( struct MHD_Connection *connection, const struct TALER_CoinPublicInfo *coin, + const struct TALER_ExchangeWithdrawValues *exchange_vals, const union TALER_DenominationBlindingKeyP *coin_bks, + const struct TALER_CsNonce *nonce, const struct TALER_CoinSpendSignatureP *coin_sig) { struct RecoupContext pc; @@ -241,18 +245,17 @@ verify_and_execute_recoup_refresh ( } { - void *coin_ev; - size_t coin_ev_size; struct TALER_CoinPubHash c_hash; + struct TALER_BlindedPlanchet blinded_planchet; if (GNUNET_OK != TALER_denom_blind (&dk->denom_pub, coin_bks, NULL, /* FIXME-Oec: TALER_AgeCommitmentHash * */ &coin->coin_pub, + exchange_vals, &c_hash, - &coin_ev, - &coin_ev_size)) + &blinded_planchet)) { GNUNET_break (0); return TALER_MHD_reply_with_error ( @@ -261,10 +264,13 @@ verify_and_execute_recoup_refresh ( TALER_EC_EXCHANGE_RECOUP_REFRESH_BLINDING_FAILED, NULL); } - TALER_coin_ev_hash (coin_ev, - coin_ev_size, + if (TALER_DENOMINATION_CS == blinded_planchet.cipher) + blinded_planchet.details.cs_blinded_planchet.nonce + = *nonce; + TALER_coin_ev_hash (&blinded_planchet, + &coin->denom_pub_hash, &h_blind); - GNUNET_free (coin_ev); + TALER_blinded_planchet_free (&blinded_planchet); } pc.coin_sig = coin_sig; @@ -357,21 +363,31 @@ TEH_handler_recoup_refresh (struct MHD_Connection *connection, struct TALER_CoinPublicInfo coin; union TALER_DenominationBlindingKeyP coin_bks; struct TALER_CoinSpendSignatureP coin_sig; + struct TALER_ExchangeWithdrawValues exchange_vals; + struct TALER_CsNonce nonce; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_fixed_auto ("denom_pub_hash", &coin.denom_pub_hash), TALER_JSON_spec_denom_sig ("denom_sig", &coin.denom_sig), + TALER_JSON_spec_exchange_withdraw_values ("ewv", + &exchange_vals), GNUNET_JSON_spec_fixed_auto ("coin_blind_key_secret", &coin_bks), GNUNET_JSON_spec_fixed_auto ("coin_sig", &coin_sig), + GNUNET_JSON_spec_mark_optional ( + GNUNET_JSON_spec_fixed_auto ("cs_nonce", + &nonce)), GNUNET_JSON_spec_end () }; memset (&coin, 0, sizeof (coin)); + memset (&nonce, + 0, + sizeof (nonce)); coin.coin_pub = *coin_pub; ret = TALER_MHD_parse_json_data (connection, root, @@ -385,7 +401,9 @@ TEH_handler_recoup_refresh (struct MHD_Connection *connection, res = verify_and_execute_recoup_refresh (connection, &coin, + &exchange_vals, &coin_bks, + &nonce, &coin_sig); GNUNET_JSON_parse_free (spec); return res; diff --git a/src/exchange/taler-exchange-httpd_recoup-refresh.h b/src/exchange/taler-exchange-httpd_recoup-refresh.h index 25c12fac3..94ae7f889 100644 --- a/src/exchange/taler-exchange-httpd_recoup-refresh.h +++ b/src/exchange/taler-exchange-httpd_recoup-refresh.h @@ -14,7 +14,7 @@ TALER; see the file COPYING. If not, see */ /** - * @file taler-exchange-httpd_recoup_refresh.h + * @file taler-exchange-httpd_recoup-refresh.h * @brief Handle /recoup-refresh requests * @author Christian Grothoff */ diff --git a/src/exchange/taler-exchange-httpd_recoup.c b/src/exchange/taler-exchange-httpd_recoup.c index 9b1ba8224..4ac997e9c 100644 --- a/src/exchange/taler-exchange-httpd_recoup.c +++ b/src/exchange/taler-exchange-httpd_recoup.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2017-2021 Taler Systems SA + Copyright (C) 2017-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -40,9 +40,9 @@ struct RecoupContext { /** - * Hash of the blinded coin. + * Hash identifying the withdraw request. */ - struct TALER_BlindedCoinHash h_blind; + struct TALER_WithdrawIdentificationHash wih; /** * Set by #recoup_transaction() to the reserve that will @@ -165,6 +165,8 @@ recoup_transaction (void *cls, * * @param connection the MHD connection to handle * @param coin information about the coin + * @param exchange_vals values contributed by the exchange + * during withdrawal * @param coin_bks blinding data of the coin (to be checked) * @param coin_sig signature of the coin * @return MHD result code @@ -173,7 +175,9 @@ static MHD_RESULT verify_and_execute_recoup ( struct MHD_Connection *connection, const struct TALER_CoinPublicInfo *coin, + const struct TALER_ExchangeWithdrawValues *exchange_vals, const union TALER_DenominationBlindingKeyP *coin_bks, + const struct TALER_CsNonce *nonce, const struct TALER_CoinSpendSignatureP *coin_sig) { struct RecoupContext pc; @@ -242,19 +246,21 @@ verify_and_execute_recoup ( NULL); } + /* re-compute client-side blinding so we can + (a bit later) check that this coin was indeed + signed by us. */ { - void *coin_ev; - size_t coin_ev_size; struct TALER_CoinPubHash c_hash; + struct TALER_BlindedPlanchet blinded_planchet; if (GNUNET_OK != TALER_denom_blind (&dk->denom_pub, coin_bks, NULL, /* FIXME-Oec: TALER_AgeCommitmentHash * */ &coin->coin_pub, + exchange_vals, &c_hash, - &coin_ev, - &coin_ev_size)) + &blinded_planchet)) { GNUNET_break (0); return TALER_MHD_reply_with_error ( @@ -263,10 +269,21 @@ verify_and_execute_recoup ( TALER_EC_EXCHANGE_RECOUP_BLINDING_FAILED, NULL); } - TALER_coin_ev_hash (coin_ev, - coin_ev_size, - &pc.h_blind); - GNUNET_free (coin_ev); + if (TALER_DENOMINATION_CS == blinded_planchet.cipher) + blinded_planchet.details.cs_blinded_planchet.nonce + = *nonce; + if (GNUNET_OK != + TALER_withdraw_request_hash (&blinded_planchet, + &coin->denom_pub_hash, + &pc.wih)) + { + GNUNET_break (0); + return TALER_MHD_reply_with_error (connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE, + NULL); + } + TALER_blinded_planchet_free (&blinded_planchet); } pc.coin_sig = coin_sig; @@ -291,10 +308,10 @@ verify_and_execute_recoup ( { enum GNUNET_DB_QueryStatus qs; - qs = TEH_plugin->get_reserve_by_h_blind (TEH_plugin->cls, - &pc.h_blind, - &pc.reserve_pub, - &pc.reserve_out_serial_id); + qs = TEH_plugin->get_reserve_by_wih (TEH_plugin->cls, + &pc.wih, + &pc.reserve_pub, + &pc.reserve_out_serial_id); if (0 > qs) { GNUNET_break (0); @@ -302,13 +319,13 @@ verify_and_execute_recoup ( connection, MHD_HTTP_INTERNAL_SERVER_ERROR, TALER_EC_GENERIC_DB_FETCH_FAILED, - "get_reserve_by_h_blind"); + "get_reserve_by_wih"); } if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs) { GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Recoup requested for unknown envelope %s\n", - GNUNET_h2s (&pc.h_blind.hash)); + GNUNET_h2s (&pc.wih.hash)); return TALER_MHD_reply_with_error ( connection, MHD_HTTP_NOT_FOUND, @@ -359,21 +376,31 @@ TEH_handler_recoup (struct MHD_Connection *connection, struct TALER_CoinPublicInfo coin; union TALER_DenominationBlindingKeyP coin_bks; struct TALER_CoinSpendSignatureP coin_sig; + struct TALER_ExchangeWithdrawValues exchange_vals; + struct TALER_CsNonce nonce; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_fixed_auto ("denom_pub_hash", &coin.denom_pub_hash), TALER_JSON_spec_denom_sig ("denom_sig", &coin.denom_sig), + TALER_JSON_spec_exchange_withdraw_values ("ewv", + &exchange_vals), GNUNET_JSON_spec_fixed_auto ("coin_blind_key_secret", &coin_bks), GNUNET_JSON_spec_fixed_auto ("coin_sig", &coin_sig), + GNUNET_JSON_spec_mark_optional ( + GNUNET_JSON_spec_fixed_auto ("cs_nonce", + &nonce)), GNUNET_JSON_spec_end () }; memset (&coin, 0, sizeof (coin)); + memset (&nonce, + 0, + sizeof (nonce)); coin.coin_pub = *coin_pub; ret = TALER_MHD_parse_json_data (connection, root, @@ -382,12 +409,17 @@ TEH_handler_recoup (struct MHD_Connection *connection, return MHD_NO; /* hard failure */ if (GNUNET_NO == ret) return MHD_YES; /* failure */ + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Recoup coin with BKS=%s\n", + TALER_B2S (&coin_bks)); { MHD_RESULT res; res = verify_and_execute_recoup (connection, &coin, + &exchange_vals, &coin_bks, + &nonce, &coin_sig); GNUNET_JSON_parse_free (spec); return res; diff --git a/src/exchange/taler-exchange-httpd_refreshes_reveal.c b/src/exchange/taler-exchange-httpd_refreshes_reveal.c index aae87290e..1f0782aaa 100644 --- a/src/exchange/taler-exchange-httpd_refreshes_reveal.c +++ b/src/exchange/taler-exchange-httpd_refreshes_reveal.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2019, 2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -31,18 +31,12 @@ #include "taler-exchange-httpd_keys.h" -/** - * Maximum number of fresh coins we allow per refresh operation. - */ -#define MAX_FRESH_COINS 256 - - /** * Send a response for "/refreshes/$RCH/reveal". * * @param connection the connection to send the response to * @param num_freshcoins number of new coins for which we reveal data - * @param sigs array of @a num_freshcoins signatures revealed + * @param rrcs array of @a num_freshcoins signatures revealed * @return a MHD result code */ static MHD_RESULT @@ -108,6 +102,14 @@ struct RevealContext */ const struct TEH_DenominationKey **dks; + /** + * Array of information about fresh coins being revealed. + */ + /* FIXME: const would be nicer here, but we initalize + the 'alg_values' in the verification + routine; suboptimal to be fixed... */ + struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrcs; + /** * Envelopes to be signed. */ @@ -142,6 +144,79 @@ check_commitment (struct RevealContext *rctx, struct MHD_Connection *connection, MHD_RESULT *mhd_ret) { + struct TALER_CsNonce nonces[rctx->num_fresh_coins]; + unsigned int aoff = 0; + + for (unsigned int j = 0; jnum_fresh_coins; j++) + { + const struct TALER_DenominationPublicKey *dk = &rctx->dks[j]->denom_pub; + + if (dk->cipher != rctx->rcds[j].blinded_planchet.cipher) + { + GNUNET_break (0); + *mhd_ret = TALER_MHD_reply_with_error ( + connection, + MHD_HTTP_BAD_REQUEST, + TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH, + NULL); + return GNUNET_SYSERR; + } + switch (dk->cipher) + { + case TALER_DENOMINATION_INVALID: + GNUNET_break (0); + *mhd_ret = TALER_MHD_reply_with_error ( + connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE, + NULL); + return GNUNET_SYSERR; + case TALER_DENOMINATION_RSA: + continue; + case TALER_DENOMINATION_CS: + nonces[aoff] + = rctx->rcds[j].blinded_planchet.details.cs_blinded_planchet.nonce; + aoff++; + break; + } + } + + // OPTIMIZE: do this in batch later! + aoff = 0; + for (unsigned int j = 0; jnum_fresh_coins; j++) + { + const struct TALER_DenominationPublicKey *dk = &rctx->dks[j]->denom_pub; + struct TALER_ExchangeWithdrawValues *alg_values + = &rctx->rrcs[j].exchange_vals; + + alg_values->cipher = dk->cipher; + switch (dk->cipher) + { + case TALER_DENOMINATION_INVALID: + GNUNET_assert (0); + return GNUNET_SYSERR; + case TALER_DENOMINATION_RSA: + continue; + case TALER_DENOMINATION_CS: + { + enum TALER_ErrorCode ec; + + ec = TEH_keys_denomination_cs_r_pub ( + &rctx->rrcs[j].h_denom_pub, + &nonces[aoff], + &alg_values->details.cs_values); + if (TALER_EC_NONE != ec) + { + *mhd_ret = TALER_MHD_reply_with_error (connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + ec, + NULL); + return GNUNET_SYSERR; + } + aoff++; + } + } + } /* Verify commitment */ { /* Note that the contents of rcs[melt.session.noreveal_index] @@ -177,25 +252,45 @@ check_commitment (struct RevealContext *rctx, &ts); rce->new_coins = GNUNET_new_array (rctx->num_fresh_coins, struct TALER_RefreshCoinData); + aoff = 0; for (unsigned int j = 0; jnum_fresh_coins; j++) { + const struct TALER_DenominationPublicKey *dk + = &rctx->dks[j]->denom_pub; struct TALER_RefreshCoinData *rcd = &rce->new_coins[j]; - struct TALER_PlanchetSecretsP ps; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; + const struct TALER_ExchangeWithdrawValues *alg_value + = &rctx->rrcs[j].exchange_vals; struct TALER_PlanchetDetail pd; struct TALER_CoinPubHash c_hash; + struct TALER_PlanchetMasterSecretP ps; rcd->dk = &rctx->dks[j]->denom_pub; - TALER_planchet_setup_refresh (&ts, - j, - &ps); + TALER_transfer_secret_to_planchet_secret (&ts, + j, + &ps); + TALER_planchet_setup_coin_priv (&ps, + alg_value, + &coin_priv); + TALER_planchet_blinding_secret_create (&ps, + alg_value, + &bks); GNUNET_assert (GNUNET_OK == TALER_planchet_prepare (rcd->dk, - &ps, + alg_value, + &bks, + &coin_priv, NULL, /* FIXME-Oec, struct TALER_AgeCommitmentHash * */ &c_hash, &pd)); - rcd->coin_ev = pd.coin_ev; - rcd->coin_ev_size = pd.coin_ev_size; + if (TALER_DENOMINATION_CS == dk->cipher) + { + pd.blinded_planchet.details.cs_blinded_planchet.nonce = + nonces[aoff]; + aoff++; + } + rcd->blinded_planchet = pd.blinded_planchet; } } } @@ -217,7 +312,7 @@ check_commitment (struct RevealContext *rctx, { struct TALER_RefreshCoinData *rcd = &rce->new_coins[j]; - GNUNET_free (rcd->coin_ev); + TALER_blinded_planchet_free (&rcd->blinded_planchet); } GNUNET_free (rce->new_coins); } @@ -299,7 +394,7 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, const json_t *coin_evs) { unsigned int num_fresh_coins = json_array_size (new_denoms_h_json); - /* We know num_fresh_coins is bounded by #MAX_FRESH_COINS, so this is safe */ + /* We know num_fresh_coins is bounded by #TALER_MAX_FRESH_COINS, so this is safe */ const struct TEH_DenominationKey *dks[num_fresh_coins]; struct TALER_RefreshCoinData rcds[num_fresh_coins]; struct TALER_EXCHANGEDB_RefreshRevealedCoin rrcs[num_fresh_coins]; @@ -379,9 +474,8 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, { struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrc = &rrcs[i]; struct GNUNET_JSON_Specification spec[] = { - GNUNET_JSON_spec_varsize (NULL, - &rrc->coin_ev, - &rrc->coin_ev_size), + TALER_JSON_spec_blinded_planchet (NULL, + &rrc->blinded_planchet), GNUNET_JSON_spec_end () }; enum GNUNET_GenericReturnValue res; @@ -394,12 +488,12 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, if (GNUNET_OK != res) { for (unsigned int j = 0; jcoin_ev, - rrc->coin_ev_size, - &rrc->coin_envelope_hash.hash); + TALER_coin_ev_hash (&rrc->blinded_planchet, + &rrcs[i].h_denom_pub, + &rrc->coin_envelope_hash); } /* lookup old_coin_pub in database */ @@ -492,13 +586,23 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, const struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrc = &rrcs[i]; struct TALER_RefreshCoinData *rcd = &rcds[i]; - rcd->coin_ev = rrc->coin_ev; - rcd->coin_ev_size = rrc->coin_ev_size; + rcd->blinded_planchet = rrc->blinded_planchet; rcd->dk = &dks[i]->denom_pub; + if (rcd->blinded_planchet.cipher != rcd->dk->cipher) + { + GNUNET_break_op (0); + ret = TALER_MHD_REPLY_JSON_PACK ( + connection, + MHD_HTTP_BAD_REQUEST, + TALER_JSON_pack_ec ( + TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH)); + goto cleanup; + } } rctx->dks = dks; rctx->rcds = rcds; + rctx->rrcs = rrcs; if (GNUNET_OK != check_commitment (rctx, connection, @@ -512,14 +616,12 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, /* create fresh coin signatures */ for (unsigned int i = 0; inum_fresh_coins; i++) { - enum TALER_ErrorCode ec = TALER_EC_NONE; + enum TALER_ErrorCode ec; - rrcs[i].coin_sig - = TEH_keys_denomination_sign ( - &rrcs[i].h_denom_pub, - rcds[i].coin_ev, - rcds[i].coin_ev_size, - &ec); + ec = TEH_keys_denomination_sign ( + &rrcs[i].h_denom_pub, + &rcds[i].blinded_planchet, + &rrcs[i].coin_sig); if (TALER_EC_NONE != ec) { GNUNET_break (0); @@ -541,8 +643,7 @@ resolve_refreshes_reveal_denominations (struct MHD_Connection *connection, { struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrc = &rrcs[i]; - rrc->coin_ev = rcds[i].coin_ev; - rrc->coin_ev_size = rcds[i].coin_ev_size; + rrc->blinded_planchet = rcds[i].blinded_planchet; } qs = TEH_plugin->insert_refresh_reveal (TEH_plugin->cls, melt_serial_id, @@ -575,7 +676,7 @@ cleanup: struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrc = &rrcs[i]; TALER_blinded_denom_sig_free (&rrc->coin_sig); - GNUNET_free (rrc->coin_ev); + TALER_blinded_planchet_free (&rrc->blinded_planchet); } return ret; } @@ -616,13 +717,13 @@ handle_refreshes_reveal_json (struct MHD_Connection *connection, unsigned int num_tprivs = json_array_size (tp_json); GNUNET_assert (num_tprivs == TALER_CNC_KAPPA - 1); /* checked just earlier */ - if ( (num_fresh_coins >= MAX_FRESH_COINS) || + if ( (num_fresh_coins >= TALER_MAX_FRESH_COINS) || (0 == num_fresh_coins) ) { GNUNET_break_op (0); return TALER_MHD_reply_with_error (connection, MHD_HTTP_BAD_REQUEST, - TALER_EC_EXCHANGE_REFRESHES_REVEAL_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE, + TALER_EC_EXCHANGE_GENERIC_NEW_DENOMS_ARRAY_SIZE_EXCESSIVE, NULL); } diff --git a/src/exchange/taler-exchange-httpd_responses.c b/src/exchange/taler-exchange-httpd_responses.c index 96bff2eff..00f047172 100644 --- a/src/exchange/taler-exchange-httpd_responses.c +++ b/src/exchange/taler-exchange-httpd_responses.c @@ -503,18 +503,53 @@ TEH_RESPONSE_reply_expired_denom_pub_hash ( } -/** - * Send proof that a request is invalid to client because of - * insufficient funds. This function will create a message with all - * of the operations affecting the coin that demonstrate that the coin - * has insufficient value. - * - * @param connection connection to the client - * @param ec error code to return - * @param coin_pub public key of the coin - * @param tl transaction list to use to build reply - * @return MHD result code - */ +MHD_RESULT +TEH_RESPONSE_reply_invalid_denom_cipher_for_operation ( + struct MHD_Connection *connection, + const struct TALER_DenominationHash *dph) +{ + struct TALER_ExchangePublicKeyP epub; + struct TALER_ExchangeSignatureP esig; + struct GNUNET_TIME_Timestamp now; + enum TALER_ErrorCode ec; + + now = GNUNET_TIME_timestamp_get (); + { + struct TALER_DenominationUnknownAffirmationPS dua = { + .purpose.size = htonl (sizeof (dua)), + .purpose.purpose = htonl (TALER_SIGNATURE_EXCHANGE_AFFIRM_DENOM_UNKNOWN), + .timestamp = GNUNET_TIME_timestamp_hton (now), + .h_denom_pub = *dph, + }; + + ec = TEH_keys_exchange_sign (&dua, + &epub, + &esig); + } + if (TALER_EC_NONE != ec) + { + GNUNET_break (0); + return TALER_MHD_reply_with_error (connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + ec, + NULL); + } + return TALER_MHD_REPLY_JSON_PACK ( + connection, + MHD_HTTP_NOT_FOUND, + TALER_JSON_pack_ec ( + TALER_EC_EXCHANGE_GENERIC_INVALID_DENOMINATION_CIPHER_FOR_OPERATION), + GNUNET_JSON_pack_timestamp ("timestamp", + now), + GNUNET_JSON_pack_data_auto ("exchange_pub", + &epub), + GNUNET_JSON_pack_data_auto ("exchange_sig", + &esig), + GNUNET_JSON_pack_data_auto ("h_denom_pub", + dph)); +} + + MHD_RESULT TEH_RESPONSE_reply_coin_insufficient_funds ( struct MHD_Connection *connection, diff --git a/src/exchange/taler-exchange-httpd_responses.h b/src/exchange/taler-exchange-httpd_responses.h index db2286ffa..48309a41d 100644 --- a/src/exchange/taler-exchange-httpd_responses.h +++ b/src/exchange/taler-exchange-httpd_responses.h @@ -79,6 +79,19 @@ TEH_RESPONSE_reply_expired_denom_pub_hash ( const char *oper); +/** + * Send assertion that the given denomination cannot be used for this operation. + * + * @param connection connection to the client + * @param dph denomination public key hash + * @return MHD result code + */ +MHD_RESULT +TEH_RESPONSE_reply_invalid_denom_cipher_for_operation ( + struct MHD_Connection *connection, + const struct TALER_DenominationHash *dph); + + /** * Send proof that a request is invalid to client because of * insufficient funds. This function will create a message with all diff --git a/src/exchange/taler-exchange-httpd_wire.c b/src/exchange/taler-exchange-httpd_wire.c index d378bdabc..e80c775ef 100644 --- a/src/exchange/taler-exchange-httpd_wire.c +++ b/src/exchange/taler-exchange-httpd_wire.c @@ -107,7 +107,7 @@ wire_update_event_cb (void *cls, } -int +enum GNUNET_GenericReturnValue TEH_wire_init () { struct GNUNET_DB_EventHeaderP es = { @@ -147,8 +147,7 @@ TEH_wire_done () /** - * Create standard JSON response format using - * @param ec and @a detail + * Create standard JSON response format using @a ec and @a detail. * * @param ec error code to return * @param detail optional detail text to return, can be NULL diff --git a/src/exchange/taler-exchange-httpd_withdraw.c b/src/exchange/taler-exchange-httpd_withdraw.c index 53ba270ba..a3ac1de33 100644 --- a/src/exchange/taler-exchange-httpd_withdraw.c +++ b/src/exchange/taler-exchange-httpd_withdraw.c @@ -90,20 +90,31 @@ reply_withdraw_insufficient_funds ( */ struct WithdrawContext { + /** - * Details about the withdrawal request. + * Hash that uniquely identifies the withdraw request. */ - struct TALER_WithdrawRequestPS wsrd; + struct TALER_WithdrawIdentificationHash wih; + + /** + * Hash of the (blinded) message to be signed by the Exchange. + */ + struct TALER_BlindedCoinHash h_coin_envelope; + + /** + * Value of the coin being exchanged (matching the denomination key) + * plus the transaction fee. We include this in what is being + * signed so that we can verify a reserve's remaining total balance + * without needing to access the respective denomination key + * information each time. + */ + struct TALER_Amount amount_with_fee; + /** * Blinded planchet. */ - void *blinded_msg; - - /** - * Number of bytes in @e blinded_msg. - */ - size_t blinded_msg_len; + struct TALER_BlindedPlanchet blinded_planchet; /** * Set to the resulting signed coin data to be returned to the client. @@ -148,9 +159,8 @@ withdraw_transaction (void *cls, uint64_t ruuid; now = GNUNET_TIME_timestamp_get (); - wc->collectable.reserve_pub = wc->wsrd.reserve_pub; - wc->collectable.h_coin_envelope = wc->wsrd.h_coin_envelope; qs = TEH_plugin->do_withdraw (TEH_plugin->cls, + &wc->wih, &wc->collectable, now, &found, @@ -178,7 +188,6 @@ withdraw_transaction (void *cls, { struct TALER_EXCHANGEDB_ReserveHistory *rh; struct TALER_Amount balance; - struct TALER_Amount requested_amount; TEH_plugin->rollback (TEH_plugin->cls); // FIXME: maybe start read-committed here? @@ -197,7 +206,7 @@ withdraw_transaction (void *cls, /* The reserve does not have the required amount (actual * amount + withdraw fee) */ qs = TEH_plugin->get_reserve_history (TEH_plugin->cls, - &wc->wsrd.reserve_pub, + &wc->collectable.reserve_pub, &balance, &rh); if (NULL == rh) @@ -209,12 +218,11 @@ withdraw_transaction (void *cls, "reserve history"); return GNUNET_DB_STATUS_HARD_ERROR; } - TALER_amount_ntoh (&requested_amount, - &wc->wsrd.amount_with_fee); - *mhd_ret = reply_withdraw_insufficient_funds (connection, - &balance, - &requested_amount, - rh); + *mhd_ret = reply_withdraw_insufficient_funds ( + connection, + &balance, + &wc->collectable.amount_with_fee, + rh); TEH_plugin->free_reserve_history (TEH_plugin->cls, rh); return GNUNET_DB_STATUS_HARD_ERROR; @@ -292,7 +300,7 @@ check_request_idempotent (struct TEH_RequestContext *rc, enum GNUNET_DB_QueryStatus qs; qs = TEH_plugin->get_withdraw_info (TEH_plugin->cls, - &wc->wsrd.h_coin_envelope, + &wc->wih, &wc->collectable); if (0 > qs) { @@ -324,13 +332,12 @@ TEH_handler_withdraw (struct TEH_RequestContext *rc, { struct WithdrawContext wc; struct GNUNET_JSON_Specification spec[] = { - GNUNET_JSON_spec_varsize ("coin_ev", - &wc.blinded_msg, - &wc.blinded_msg_len), GNUNET_JSON_spec_fixed_auto ("reserve_sig", &wc.collectable.reserve_sig), GNUNET_JSON_spec_fixed_auto ("denom_pub_hash", &wc.collectable.denom_pub_hash), + TALER_JSON_spec_blinded_planchet ("coin_ev", + &wc.blinded_planchet), GNUNET_JSON_spec_end () }; enum TALER_ErrorCode ec; @@ -342,8 +349,8 @@ TEH_handler_withdraw (struct TEH_RequestContext *rc, if (GNUNET_OK != GNUNET_STRINGS_string_to_data (args[0], strlen (args[0]), - &wc.wsrd.reserve_pub, - sizeof (wc.wsrd.reserve_pub))) + &wc.collectable.reserve_pub, + sizeof (wc.collectable.reserve_pub))) { GNUNET_break_op (0); return TALER_MHD_reply_with_error (rc->connection, @@ -444,6 +451,15 @@ TEH_handler_withdraw (struct TEH_RequestContext *rc, GNUNET_JSON_parse_free (spec); return mret; } + if (dk->denom_pub.cipher != wc.blinded_planchet.cipher) + { + /* denomination cipher and blinded planchet cipher not the same */ + GNUNET_JSON_parse_free (spec); + return TALER_MHD_reply_with_error (rc->connection, + MHD_HTTP_BAD_REQUEST, + TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH, + NULL); + } } if (0 > @@ -457,29 +473,28 @@ TEH_handler_withdraw (struct TEH_RequestContext *rc, TALER_EC_EXCHANGE_WITHDRAW_AMOUNT_FEE_OVERFLOW, NULL); } - TALER_amount_hton (&wc.wsrd.amount_with_fee, - &wc.collectable.amount_with_fee); - // FIXME: move this logic into libtalerutil! - /* verify signature! */ - wc.wsrd.purpose.size - = htonl (sizeof (wc.wsrd)); - wc.wsrd.purpose.purpose - = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW); - wc.wsrd.h_denomination_pub - = wc.collectable.denom_pub_hash; - TALER_coin_ev_hash (wc.blinded_msg, - wc.blinded_msg_len, - &wc.wsrd.h_coin_envelope); if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify ( - TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW, - &wc.wsrd, - &wc.collectable.reserve_sig.eddsa_signature, - &wc.wsrd.reserve_pub.eddsa_pub)) + TALER_coin_ev_hash (&wc.blinded_planchet, + &wc.collectable.denom_pub_hash, + &wc.collectable.h_coin_envelope)) { - TALER_LOG_WARNING ( - "Client supplied invalid signature for withdraw request\n"); + GNUNET_break (0); + GNUNET_JSON_parse_free (spec); + return TALER_MHD_reply_with_error (rc->connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE, + NULL); + } + + if (GNUNET_OK != + TALER_wallet_withdraw_verify (&wc.collectable.denom_pub_hash, + &wc.collectable.amount_with_fee, + &wc.collectable.h_coin_envelope, + &wc.collectable.reserve_pub, + &wc.collectable.reserve_sig)) + { + GNUNET_break_op (0); GNUNET_JSON_parse_free (spec); return TALER_MHD_reply_with_error (rc->connection, MHD_HTTP_FORBIDDEN, @@ -487,13 +502,24 @@ TEH_handler_withdraw (struct TEH_RequestContext *rc, NULL); } + if (GNUNET_OK != + TALER_withdraw_request_hash (&wc.blinded_planchet, + &wc.collectable.denom_pub_hash, + &wc.wih)) + { + GNUNET_break (0); + GNUNET_JSON_parse_free (spec); + return TALER_MHD_reply_with_error (rc->connection, + MHD_HTTP_INTERNAL_SERVER_ERROR, + TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE, + NULL); + } + /* Sign before transaction! */ - ec = TALER_EC_NONE; - wc.collectable.sig - = TEH_keys_denomination_sign (&wc.collectable.denom_pub_hash, - wc.blinded_msg, - wc.blinded_msg_len, - &ec); + ec = TEH_keys_denomination_sign ( + &wc.collectable.denom_pub_hash, + &wc.blinded_planchet, + &wc.collectable.sig); if (TALER_EC_NONE != ec) { GNUNET_break (0); diff --git a/src/exchange/test_taler_exchange_httpd.conf b/src/exchange/test_taler_exchange_httpd.conf index 2adee5053..9bd4851fb 100644 --- a/src/exchange/test_taler_exchange_httpd.conf +++ b/src/exchange/test_taler_exchange_httpd.conf @@ -70,7 +70,7 @@ PASSWORD = x WIRE_GATEWAY_URL = "http://localhost:8082/3/" # Coins for the tests. -[coin_eur_ct_1] +[coin_eur_ct_1_rsa] value = EUR:0.01 duration_withdraw = 7 days duration_spend = 2 years @@ -79,9 +79,21 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 -[coin_eur_ct_10] +[coin_eur_ct_1_cs] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10_rsa] value = EUR:0.10 duration_withdraw = 7 days duration_spend = 2 years @@ -90,9 +102,21 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 -[coin_eur_1] +[coin_eur_ct_10_cs] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1_rsa] value = EUR:1 duration_withdraw = 7 days duration_spend = 2 years @@ -101,4 +125,16 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 + +[coin_eur_1_cs] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/exchange/test_taler_exchange_unix.conf b/src/exchange/test_taler_exchange_unix.conf index b9387f603..e96bfba3f 100644 --- a/src/exchange/test_taler_exchange_unix.conf +++ b/src/exchange/test_taler_exchange_unix.conf @@ -70,7 +70,7 @@ TALER_BANK_AUTH_METHOD = NONE # Coins for the tests. -[coin_eur_ct_1] +[coin_eur_ct_1_rsa] value = EUR:0.01 duration_withdraw = 7 days duration_spend = 2 years @@ -79,9 +79,21 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 -[coin_eur_ct_10] +[coin_eur_ct_1_cs] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10_rsa] value = EUR:0.10 duration_withdraw = 7 days duration_spend = 2 years @@ -90,9 +102,21 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 -[coin_eur_1] +[coin_eur_ct_10_cs] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1_rsa] value = EUR:1 duration_withdraw = 7 days duration_spend = 2 years @@ -101,4 +125,16 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 + +[coin_eur_1_cs] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/exchangedb/exchange-0001.sql b/src/exchangedb/exchange-0001.sql index d8f92b0bf..df07e0252 100644 --- a/src/exchangedb/exchange-0001.sql +++ b/src/exchangedb/exchange-0001.sql @@ -196,7 +196,8 @@ CREATE INDEX IF NOT EXISTS reserves_close_by_reserve_pub_index CREATE TABLE IF NOT EXISTS reserves_out (reserve_out_serial_id BIGSERIAL -- UNIQUE - ,h_blind_ev BYTEA PRIMARY KEY CHECK (LENGTH(h_blind_ev)=64) + ,wih BYTEA PRIMARY KEY CHECK (LENGTH(wih)=64) + ,h_blind_ev BYTEA CHECK (LENGTH(h_blind_ev)=64) -- UNIQUE ,denominations_serial INT8 NOT NULL REFERENCES denominations (denominations_serial) ,denom_sig BYTEA NOT NULL ,reserve_uuid INT8 NOT NULL -- REFERENCES reserves (reserve_uuid) ON DELETE CASCADE @@ -205,9 +206,11 @@ CREATE TABLE IF NOT EXISTS reserves_out ,amount_with_fee_val INT8 NOT NULL ,amount_with_fee_frac INT4 NOT NULL ) - PARTITION BY HASH (h_blind_ev); + PARTITION BY HASH (wih); COMMENT ON TABLE reserves_out IS 'Withdraw operations performed on reserves.'; +COMMENT ON COLUMN reserves_out.wih + IS 'Hash that uniquely identifies the withdraw request. Used to detect request replays (crucial for CS) and to check the withdraw existed during recoup.'; COMMENT ON COLUMN reserves_out.h_blind_ev IS 'Hash of the blinded coin, used as primary key here so that broken clients that use a non-random coin or blinding factor fail to withdraw (otherwise they would fail on deposit when the coin is not unique there).'; COMMENT ON COLUMN reserves_out.denominations_serial @@ -380,6 +383,7 @@ CREATE TABLE IF NOT EXISTS refresh_revealed_coins ,coin_ev BYTEA NOT NULL -- UNIQUE ,h_coin_ev BYTEA NOT NULL CHECK(LENGTH(h_coin_ev)=64) -- UNIQUE ,ev_sig BYTEA NOT NULL + ,ewv BYTEA NOT NULL -- ,PRIMARY KEY (melt_serial_id, freshcoin_index) -- done per shard ) PARTITION BY HASH (melt_serial_id); @@ -393,6 +397,8 @@ COMMENT ON COLUMN refresh_revealed_coins.freshcoin_index IS 'index of the fresh coin being created (one melt operation may result in multiple fresh coins)'; COMMENT ON COLUMN refresh_revealed_coins.coin_ev IS 'envelope of the new coin to be signed'; +COMMENT ON COLUMN refresh_revealed_coins.ewv + IS 'exchange contributed values in the creation of the fresh coin (see /csr)'; COMMENT ON COLUMN refresh_revealed_coins.h_coin_ev IS 'hash of the envelope of the new coin to be signed (for lookups)'; COMMENT ON COLUMN refresh_revealed_coins.ev_sig @@ -637,7 +643,7 @@ COMMENT ON TABLE recoup COMMENT ON COLUMN recoup.known_coin_id IS 'Coin that is being debited in the recoup. Do not CASCADE ON DROP on the coin_pub, as we may keep the coin alive!'; COMMENT ON COLUMN recoup.reserve_out_serial_id - IS 'Identifies the h_blind_ev of the recouped coin and provides the link to the credited reserve.'; + IS 'Identifies the wih of the recouped coin and provides the link to the credited reserve.'; COMMENT ON COLUMN recoup.coin_sig IS 'Signature by the coin affirming the recoup, of type TALER_SIGNATURE_WALLET_COIN_RECOUP'; COMMENT ON COLUMN recoup.coin_blind @@ -812,6 +818,7 @@ CREATE INDEX IF NOT EXISTS revolving_work_shards_by_job_name_active_last_attempt CREATE OR REPLACE FUNCTION exchange_do_withdraw( + IN in_wih BYTEA, IN amount_val INT8, IN amount_frac INT4, IN h_denom_pub BYTEA, @@ -825,7 +832,8 @@ CREATE OR REPLACE FUNCTION exchange_do_withdraw( OUT balance_ok BOOLEAN, OUT kycok BOOLEAN, OUT account_uuid INT8, - OUT ruuid INT8) + OUT ruuid INT8, + OUT out_denom_sig BYTEA) LANGUAGE plpgsql AS $$ DECLARE @@ -838,7 +846,7 @@ DECLARE reserve_frac INT4; BEGIN -- Shards: reserves by reserve_pub (SELECT) --- reserves_out (INSERT, with CONFLICT detection) by h_blind_ev +-- reserves_out (INSERT, with CONFLICT detection) by wih -- reserves by reserve_pub (UPDATE) -- reserves_in by reserve_pub (SELECT) -- wire_targets by wire_target_serial_id @@ -887,6 +895,7 @@ END IF; -- the query successful due to idempotency. INSERT INTO reserves_out (h_blind_ev + ,wih ,denominations_serial ,denom_sig ,reserve_uuid @@ -896,6 +905,7 @@ INSERT INTO reserves_out ,amount_with_fee_frac) VALUES (h_coin_envelope + ,in_wih ,denom_serial ,denom_sig ,ruuid @@ -908,6 +918,25 @@ ON CONFLICT DO NOTHING; IF NOT FOUND THEN -- idempotent query, all constraints must be satisfied + + SELECT + denom_sig + INTO + out_denom_sig + FROM reserves_in + WHERE wih=in_wih + LIMIT 1; -- limit 1 should not be required (without p2p transfers) + + IF NOT FOUND + THEN + reserve_found=FALSE; + balance_ok=FALSE; + kycok=FALSE; + account_uuid=0; + ruuid=0; + ASSERT false, 'internal logic error'; + END IF; + reserve_found=TRUE; balance_ok=TRUE; kycok=TRUE; @@ -967,9 +996,13 @@ SELECT WHERE reserve_pub=rpub LIMIT 1; -- limit 1 should not be required (without p2p transfers) +-- Return denomination signature as result that +-- was given as the argument. +out_denom_sig=denom_sig; + END $$; -COMMENT ON FUNCTION exchange_do_withdraw(INT8, INT4, BYTEA, BYTEA, BYTEA, BYTEA, BYTEA, INT8, INT8) +COMMENT ON FUNCTION exchange_do_withdraw(BYTEA, INT8, INT4, BYTEA, BYTEA, BYTEA, BYTEA, BYTEA, INT8, INT8) IS 'Checks whether the reserve has sufficient balance for a withdraw operation (or the request is repeated and was previously approved) and if so updates the database with the result'; diff --git a/src/exchangedb/exchangedb_transactions.c b/src/exchangedb/exchangedb_transactions.c index aaf28a9ea..81a33b172 100644 --- a/src/exchangedb/exchangedb_transactions.c +++ b/src/exchangedb/exchangedb_transactions.c @@ -22,17 +22,7 @@ #include "taler_exchangedb_lib.h" -/** - * Calculate the total value of all transactions performed. - * Stores @a off plus the cost of all transactions in @a tl - * in @a ret. - * - * @param tl transaction list to process - * @param off offset to use as the starting value - * @param[out] ret where the resulting total is to be stored (may alias @a off) - * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors - */ -int +enum GNUNET_GenericReturnValue TALER_EXCHANGEDB_calculate_transaction_list_totals ( struct TALER_EXCHANGEDB_TransactionList *tl, const struct TALER_Amount *off, diff --git a/src/exchangedb/irbt_callbacks.c b/src/exchangedb/irbt_callbacks.c index 0e0264e89..cb0685ba6 100644 --- a/src/exchangedb/irbt_callbacks.c +++ b/src/exchangedb/irbt_callbacks.c @@ -440,6 +440,8 @@ irbt_cb_table_refresh_revealed_coins ( GNUNET_PQ_query_param_auto_from_type (&h_coin_ev), TALER_PQ_query_param_blinded_denom_sig ( &td->details.refresh_revealed_coins.ev_sig), + TALER_PQ_query_param_exchange_withdraw_values ( + &td->details.refresh_revealed_coins.ewv), GNUNET_PQ_query_param_uint64 ( &td->details.refresh_revealed_coins.denominations_serial), GNUNET_PQ_query_param_uint64 ( diff --git a/src/exchangedb/lrbt_callbacks.c b/src/exchangedb/lrbt_callbacks.c index 04be98696..dd7852131 100644 --- a/src/exchangedb/lrbt_callbacks.c +++ b/src/exchangedb/lrbt_callbacks.c @@ -790,6 +790,9 @@ lrbt_cb_table_refresh_revealed_coins (void *cls, TALER_PQ_result_spec_blinded_denom_sig ( "ev_sig", &td.details.refresh_revealed_coins.ev_sig), + TALER_PQ_result_spec_exchange_withdraw_values ( + "ewv", + &td.details.refresh_revealed_coins.ewv), GNUNET_PQ_result_spec_uint64 ( "denominations_serial", &td.details.refresh_revealed_coins.denominations_serial), diff --git a/src/exchangedb/plugin_exchangedb_postgres.c b/src/exchangedb/plugin_exchangedb_postgres.c index c0ff9acdf..878c36f96 100644 --- a/src/exchangedb/plugin_exchangedb_postgres.c +++ b/src/exchangedb/plugin_exchangedb_postgres.c @@ -564,13 +564,6 @@ prepare_statements (struct PostgresClosure *pg) " ON (wire_source_serial_id = wire_target_serial_id)" " WHERE reserve_pub=$1;", 1), - /* Lock withdraw table; NOTE: we may want to eventually shard the - deposit table to avoid this lock being the main point of - contention limiting transaction performance. */ - GNUNET_PQ_make_prepare ( - "lock_withdraw", - "LOCK TABLE reserves_out;", - 0), /* Used in #postgres_do_withdraw() to store the signature of a blinded coin with the blinded coin's details before returning it during /reserve/withdraw. We store @@ -586,9 +579,10 @@ prepare_statements (struct PostgresClosure *pg) ",kycok AS kyc_ok" ",account_uuid AS payment_target_uuid" ",ruuid" + ",out_denom_sig" " FROM exchange_do_withdraw" - " ($1,$2,$3,$4,$5,$6,$7,$8,$9);", - 9), + " ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10);", + 10), /* Used in #postgres_do_withdraw_limit_check() to check if the withdrawals remain below the limit under which KYC is not required. */ @@ -663,6 +657,7 @@ prepare_statements (struct PostgresClosure *pg) ",reserve_sig" ",reserves.reserve_pub" ",execution_date" + ",h_blind_ev" ",amount_with_fee_val" ",amount_with_fee_frac" ",denom.fee_withdraw_val" @@ -672,7 +667,7 @@ prepare_statements (struct PostgresClosure *pg) " USING (reserve_uuid)" " JOIN denominations denom" " USING (denominations_serial)" - " WHERE h_blind_ev=$1;", + " WHERE wih=$1;", 1), /* Used during #postgres_get_reserve_history() to obtain all of the /reserve/withdraw operations that @@ -897,13 +892,14 @@ prepare_statements (struct PostgresClosure *pg) ",link_sig " ",denominations_serial " ",coin_ev" + ",ewv" ",h_coin_ev" ",ev_sig" ") SELECT $1, $2, $3, " - " denominations_serial, $5, $6, $7" + " denominations_serial, $5, $6, $7, $8" " FROM denominations" " WHERE denom_pub_hash=$4;", - 7), + 8), /* Obtain information about the coins created in a refresh operation, used in #postgres_get_refresh_reveal() */ GNUNET_PQ_make_prepare ( @@ -914,6 +910,7 @@ prepare_statements (struct PostgresClosure *pg) ",rrc.h_coin_ev" ",rrc.link_sig" ",rrc.coin_ev" + ",rrc.ewv" ",rrc.ev_sig" " FROM refresh_commitments" " JOIN refresh_revealed_coins rrc" @@ -1219,7 +1216,10 @@ prepare_statements (struct PostgresClosure *pg) " tp.transfer_pub" ",denoms.denom_pub" ",rrc.ev_sig" + ",rrc.ewv" ",rrc.link_sig" + ",rrc.freshcoin_index" + ",rrc.coin_ev" " FROM refresh_commitments" " JOIN refresh_revealed_coins rrc" " USING (melt_serial_id)" @@ -1672,16 +1672,16 @@ prepare_statements (struct PostgresClosure *pg) " ON (denoms.denominations_serial = coins.denominations_serial)" " WHERE coins.coin_pub=$1;", 1), - /* Used in #postgres_get_reserve_by_h_blind() */ + /* Used in #postgres_get_reserve_by_wih() */ GNUNET_PQ_make_prepare ( - "reserve_by_h_blind", + "reserve_by_wih", "SELECT" " reserves.reserve_pub" ",reserve_out_serial_id" " FROM reserves_out" " JOIN reserves" " USING (reserve_uuid)" - " WHERE h_blind_ev=$1" + " WHERE wih=$1" " LIMIT 1;", 1), /* Used in #postgres_get_old_coin_by_h_blind() */ @@ -2248,6 +2248,7 @@ prepare_statements (struct PostgresClosure *pg) ",link_sig" ",coin_ev" ",ev_sig" + ",ewv" ",denominations_serial" ",melt_serial_id" " FROM refresh_revealed_coins" @@ -2540,11 +2541,12 @@ prepare_statements (struct PostgresClosure *pg) ",coin_ev" ",h_coin_ev" ",ev_sig" + ",ewv" ",denominations_serial" ",melt_serial_id" ") VALUES " - "($1, $2, $3, $4, $5, $6, $7, $8);", - 8), + "($1, $2, $3, $4, $5, $6, $7, $8, $9);", + 9), GNUNET_PQ_make_prepare ( "insert_into_table_refresh_transfer_keys", "INSERT INTO refresh_transfer_keys" @@ -3903,9 +3905,8 @@ postgres_select_kyc_status (void *cls, * Get the KYC status for a wallet. If the status is unknown, * inserts a new status record (hence INsertSELECT). * - * @param cls the @e cls of this struct with the plugin-specific state + * @param pg the plugin-specific state * @param payto_uri the payto URI to check - * @param oauth_username user ID to store * @param[out] kyc set to the KYC status of the wallet * @return transaction status */ @@ -4327,8 +4328,7 @@ postgres_reserves_in_insert (void *cls, * key of the hash of the blinded message. * * @param cls the `struct PostgresClosure` with the plugin-specific state - * @param h_blind hash of the blinded coin to be signed (will match - * `h_coin_envelope` in the @a collectable to be returned) + * @param wih hash that uniquely identifies the withdraw operation * @param collectable corresponding collectable coin (blind signature) * if a coin is found * @return statement execution status @@ -4336,12 +4336,12 @@ postgres_reserves_in_insert (void *cls, static enum GNUNET_DB_QueryStatus postgres_get_withdraw_info ( void *cls, - const struct TALER_BlindedCoinHash *h_blind, + const struct TALER_WithdrawIdentificationHash *wih, struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable) { struct PostgresClosure *pg = cls; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (h_blind), + GNUNET_PQ_query_param_auto_from_type (wih), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec rs[] = { @@ -4353,24 +4353,15 @@ postgres_get_withdraw_info ( &collectable->reserve_sig), GNUNET_PQ_result_spec_auto_from_type ("reserve_pub", &collectable->reserve_pub), + GNUNET_PQ_result_spec_auto_from_type ("h_blind_ev", + &collectable->h_coin_envelope), TALER_PQ_RESULT_SPEC_AMOUNT ("amount_with_fee", &collectable->amount_with_fee), TALER_PQ_RESULT_SPEC_AMOUNT ("fee_withdraw", &collectable->withdraw_fee), GNUNET_PQ_result_spec_end }; -#if EXPLICIT_LOCKS - struct GNUNET_PQ_QueryParam no_params[] = { - GNUNET_PQ_query_param_end - }; - enum GNUNET_DB_QueryStatus qs; - if (0 > (qs = GNUNET_PQ_eval_prepared_non_select (pg->conn, - "lock_withdraw", - no_params))) - return qs; -#endif - collectable->h_coin_envelope = *h_blind; return GNUNET_PQ_eval_prepared_singleton_select (pg->conn, "get_withdraw_info", params, @@ -4383,19 +4374,20 @@ postgres_get_withdraw_info ( * and possibly persisting the withdrawal details. * * @param cls the `struct PostgresClosure` with the plugin-specific state - * @param collectable corresponding collectable coin (blind signature) - * if a coin is found + * @param wih hash that uniquely identifies the withdraw operation + * @param[in,out] collectable corresponding collectable coin (blind signature) if a coin is found; possibly updated if a (different) signature exists already * @param now current time (rounded) * @param[out] found set to true if the reserve was found * @param[out] balance_ok set to true if the balance was sufficient - * @param[out] kyc_ok set to true if the kyc status of the reserve is satisfied + * @param[out] kyc set to true if the kyc status of the reserve is satisfied * @param[out] ruuid set to the reserve's UUID (reserves table row) * @return query execution status */ static enum GNUNET_DB_QueryStatus postgres_do_withdraw ( void *cls, - const struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable, + const struct TALER_WithdrawIdentificationHash *wih, + struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable, struct GNUNET_TIME_Timestamp now, bool *found, bool *balance_ok, @@ -4405,6 +4397,7 @@ postgres_do_withdraw ( struct PostgresClosure *pg = cls; struct GNUNET_TIME_Timestamp gc; struct GNUNET_PQ_QueryParam params[] = { + GNUNET_PQ_query_param_auto_from_type (wih), TALER_PQ_query_param_amount (&collectable->amount_with_fee), GNUNET_PQ_query_param_auto_from_type (&collectable->denom_pub_hash), GNUNET_PQ_query_param_auto_from_type (&collectable->reserve_pub), @@ -4415,6 +4408,9 @@ postgres_do_withdraw ( GNUNET_PQ_query_param_timestamp (&gc), GNUNET_PQ_query_param_end }; + enum GNUNET_DB_QueryStatus qs; + bool no_out_sig; + struct TALER_BlindedDenominationSignature out_sig; struct GNUNET_PQ_ResultSpec rs[] = { GNUNET_PQ_result_spec_bool ("reserve_found", found), @@ -4426,18 +4422,33 @@ postgres_do_withdraw ( &kyc->payment_target_uuid), GNUNET_PQ_result_spec_uint64 ("ruuid", ruuid), + GNUNET_PQ_result_spec_allow_null ( + TALER_PQ_result_spec_blinded_denom_sig ("out_denom_sig", + &out_sig), + &no_out_sig), GNUNET_PQ_result_spec_end }; +#if 0 + memset (&out_sig, + 0, + sizeof (out_sig)); +#endif gc = GNUNET_TIME_absolute_to_timestamp ( GNUNET_TIME_absolute_add (now.abs_time, pg->legal_reserve_expiration_time)); kyc->type = TALER_EXCHANGEDB_KYC_WITHDRAW; - return GNUNET_PQ_eval_prepared_singleton_select (pg->conn, - "call_withdraw", - params, - rs); - + qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn, + "call_withdraw", + params, + rs); + if ( (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs) && + (! no_out_sig) ) + { + TALER_blinded_denom_sig_free (&collectable->sig); + collectable->sig = out_sig; + } + return qs; } @@ -4481,9 +4492,9 @@ postgres_do_withdraw_limit_check ( /** - * Compute the shard number of a given @a deposit + * Compute the shard number of a given @a merchant_pub. * - * @param deposit deposit to compute shard for + * @param merchant_pub merchant public key to compute shard for * @return shard number */ static uint64_t @@ -4513,11 +4524,11 @@ compute_shard (const struct TALER_MerchantPublicKeyP *merchant_pub) * Perform deposit operation, checking for sufficient balance * of the coin and possibly persisting the deposit details. * - * FIXME: parameters missing in description! - * * @param cls the `struct PostgresClosure` with the plugin-specific state * @param deposit deposit operation details * @param known_coin_id row of the coin in the known_coins table + * @param h_payto hash of the merchant's bank account details + * @param extension_blocked true if an extension is blocking the wire transfer * @param[in,out] exchange_timestamp time to use for the deposit (possibly updated) * @param[out] balance_ok set to true if the balance was sufficient * @param[out] in_conflict set to true if the deposit conflicted @@ -6136,8 +6147,8 @@ postgres_insert_refresh_reveal ( GNUNET_PQ_query_param_uint32 (&i), GNUNET_PQ_query_param_auto_from_type (&rrc->orig_coin_link_sig), GNUNET_PQ_query_param_auto_from_type (&rrc->h_denom_pub), - GNUNET_PQ_query_param_fixed_size (rrc->coin_ev, - rrc->coin_ev_size), + TALER_PQ_query_param_blinded_planchet (&rrc->blinded_planchet), + TALER_PQ_query_param_exchange_withdraw_values (&rrc->exchange_vals), GNUNET_PQ_query_param_auto_from_type (&rrc->coin_envelope_hash), TALER_PQ_query_param_blinded_denom_sig (&rrc->coin_sig), GNUNET_PQ_query_param_end @@ -6244,15 +6255,16 @@ add_revealed_coins (void *cls, &rrc->orig_coin_link_sig), GNUNET_PQ_result_spec_auto_from_type ("h_coin_ev", &rrc->coin_envelope_hash), - GNUNET_PQ_result_spec_variable_size ("coin_ev", - (void **) &rrc->coin_ev, - &rrc->coin_ev_size), + TALER_PQ_result_spec_blinded_planchet ("coin_ev", + &rrc->blinded_planchet), + TALER_PQ_result_spec_exchange_withdraw_values ("ewv", + &rrc->exchange_vals), TALER_PQ_result_spec_blinded_denom_sig ("ev_sig", &rrc->coin_sig), GNUNET_PQ_result_spec_end }; - if (NULL != rrc->coin_ev) + if (TALER_DENOMINATION_INVALID != rrc->blinded_planchet.cipher) { /* duplicate offset, not allowed */ GNUNET_break (0); @@ -6335,10 +6347,9 @@ cleanup: struct TALER_EXCHANGEDB_RefreshRevealedCoin *rrc = &grctx.rrcs[i]; TALER_blinded_denom_sig_free (&rrc->coin_sig); - GNUNET_free (rrc->coin_ev); + TALER_blinded_planchet_free (&rrc->blinded_planchet); } GNUNET_free (grctx.rrcs); - return qs; } @@ -6422,6 +6433,7 @@ add_ldl (void *cls, pos = GNUNET_new (struct TALER_EXCHANGEDB_LinkList); { + struct TALER_BlindedPlanchet bp; struct GNUNET_PQ_ResultSpec rs[] = { GNUNET_PQ_result_spec_auto_from_type ("transfer_pub", &transfer_pub), @@ -6429,8 +6441,14 @@ add_ldl (void *cls, &pos->orig_coin_link_sig), TALER_PQ_result_spec_blinded_denom_sig ("ev_sig", &pos->ev_sig), + GNUNET_PQ_result_spec_uint32 ("freshcoin_index", + &pos->coin_refresh_offset), + TALER_PQ_result_spec_exchange_withdraw_values ("ewv", + &pos->alg_values), TALER_PQ_result_spec_denom_pub ("denom_pub", &pos->denom_pub), + TALER_PQ_result_spec_blinded_planchet ("coin_ev", + &bp), GNUNET_PQ_result_spec_end }; @@ -6444,6 +6462,12 @@ add_ldl (void *cls, ldctx->status = GNUNET_SYSERR; return; } + if (TALER_DENOMINATION_CS == bp.cipher) + { + pos->nonce = bp.details.cs_blinded_planchet.nonce; + pos->have_nonce = true; + } + TALER_blinded_planchet_free (&bp); } if ( (NULL != ldctx->last) && (0 == GNUNET_memcmp (&transfer_pub, @@ -7223,11 +7247,10 @@ postgres_lookup_wire_transfer ( * @param merchant_pub merchant public key * @param[out] pending set to true if the transaction is still pending * @param[out] wtid wire transfer identifier, only set if @a pending is false - * @param[out] coin_contribution how much did the coin we asked about - * contribute to the total transfer value? (deposit value including fee) - * @param[out] coin_fee how much did the exchange charge for the deposit fee - * @param[out] execution_time when was the transaction done, or + * @param[out] exec_time when was the transaction done, or * when we expect it to be done (if @a pending is false) + * @param[out] amount_with_fee set to the total deposited amount + * @param[out] deposit_fee set to how much the exchange did charge for the deposit * @param[out] kyc set to the kyc status of the receiver (if @a pending) * @return transaction status code */ @@ -7254,7 +7277,7 @@ postgres_lookup_transfer_by_deposit ( GNUNET_PQ_query_param_end }; char *payto_uri; - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; struct GNUNET_PQ_ResultSpec rs[] = { GNUNET_PQ_result_spec_auto_from_type ("wtid_raw", wtid), @@ -9405,20 +9428,21 @@ postgres_select_reserve_closed_above_serial_id ( * from given the hash of the blinded coin. * * @param cls closure - * @param h_blind_ev hash of the blinded coin + * @param wih hash that uniquely identifies the withdraw request * @param[out] reserve_pub set to information about the reserve (on success only) * @param[out] reserve_out_serial_id set to row of the @a h_blind_ev in reserves_out * @return transaction status code */ static enum GNUNET_DB_QueryStatus -postgres_get_reserve_by_h_blind (void *cls, - const struct TALER_BlindedCoinHash *h_blind_ev, - struct TALER_ReservePublicKeyP *reserve_pub, - uint64_t *reserve_out_serial_id) +postgres_get_reserve_by_wih ( + void *cls, + const struct TALER_WithdrawIdentificationHash *wih, + struct TALER_ReservePublicKeyP *reserve_pub, + uint64_t *reserve_out_serial_id) { struct PostgresClosure *pg = cls; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (h_blind_ev), + GNUNET_PQ_query_param_auto_from_type (wih), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec rs[] = { @@ -9430,7 +9454,7 @@ postgres_get_reserve_by_h_blind (void *cls, }; return GNUNET_PQ_eval_prepared_singleton_select (pg->conn, - "reserve_by_h_blind", + "reserve_by_wih", params, rs); } @@ -9443,6 +9467,7 @@ postgres_get_reserve_by_h_blind (void *cls, * @param cls closure * @param h_blind_ev hash of the blinded coin * @param[out] old_coin_pub set to information about the old coin (on success only) + * @param[out] rrc_serial set to serial number of the entry in the database * @return transaction status code */ static enum GNUNET_DB_QueryStatus @@ -11697,8 +11722,8 @@ libtaler_plugin_exchangedb_postgres_init (void *cls) = &postgres_select_recoup_refresh_above_serial_id; plugin->select_reserve_closed_above_serial_id = &postgres_select_reserve_closed_above_serial_id; - plugin->get_reserve_by_h_blind - = &postgres_get_reserve_by_h_blind; + plugin->get_reserve_by_wih + = &postgres_get_reserve_by_wih; plugin->get_old_coin_by_h_blind = &postgres_get_old_coin_by_h_blind; plugin->insert_denomination_revocation diff --git a/src/exchangedb/test_exchangedb.c b/src/exchangedb/test_exchangedb.c index ffd904f20..f9e64fdc1 100644 --- a/src/exchangedb/test_exchangedb.c +++ b/src/exchangedb/test_exchangedb.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -433,10 +433,9 @@ check_refresh_reveal_cb ( &revealed_coins[cnt]; const struct TALER_EXCHANGEDB_RefreshRevealedCoin *bcoin = &rrcs[cnt]; - GNUNET_assert (acoin->coin_ev_size == bcoin->coin_ev_size); GNUNET_assert (0 == - GNUNET_memcmp (acoin->coin_ev, - bcoin->coin_ev)); + TALER_blinded_planchet_cmp (&acoin->blinded_planchet, + &bcoin->blinded_planchet)); GNUNET_assert (0 == GNUNET_memcmp (&acoin->h_denom_pub, &bcoin->h_denom_pub)); @@ -534,7 +533,7 @@ handle_link_data_cb (void *cls, break; } } - GNUNET_assert (found); + GNUNET_assert (GNUNET_NO != found); } } @@ -1348,15 +1347,22 @@ run (void *cls) unsigned int cnt; enum GNUNET_DB_QueryStatus qs; struct GNUNET_TIME_Timestamp now; - struct TALER_WireSalt salt; - union TALER_DenominationBlindingKeyP bks; + struct TALER_WireSaltP salt; struct TALER_CoinPubHash c_hash; + struct TALER_WithdrawIdentificationHash wih; uint64_t known_coin_id; uint64_t rrc_serial; struct TALER_EXCHANGEDB_Refresh refresh; struct TALER_DenominationPublicKey *new_denom_pubs = NULL; uint64_t reserve_out_serial_id; uint64_t melt_serial_id; + struct TALER_PlanchetMasterSecretP ps; + union TALER_DenominationBlindingKeyP bks; + struct TALER_ExchangeWithdrawValues alg_values = { + /* RSA is simpler, and for the DB there is no real difference between + CS and RSA, just one should be used, so we use RSA */ + .cipher = TALER_DENOMINATION_RSA + }; memset (&deposit, 0, @@ -1381,7 +1387,7 @@ run (void *cls) plugin->create_tables (plugin->cls)) { result = 77; - goto drop; + goto cleanup; } plugin->preflight (plugin->cls); FAILIF (GNUNET_OK != @@ -1418,7 +1424,6 @@ run (void *cls) GNUNET_assert (GNUNET_OK == TALER_string_to_amount (CURRENCY ":1.000010", &amount_with_fee)); - result = 4; now = GNUNET_TIME_timestamp_get (); FAILIF (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != @@ -1467,11 +1472,17 @@ run (void *cls) TALER_denom_pub_hash (&dkp->pub, &cbc.denom_pub_hash); RND_BLK (&cbc.reserve_sig); + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); { struct TALER_PlanchetDetail pd; struct TALER_CoinSpendPublicKeyP coin_pub; struct TALER_AgeCommitmentHash age_hash; - struct TALER_AgeCommitmentHash *p_ah[2] = {NULL, &age_hash}; + struct TALER_AgeCommitmentHash *p_ah[2] = { + NULL, + &age_hash + }; /* Call TALER_denom_blind()/TALER_denom_sign_blinded() twice, once without * age_hash, once with age_hash */ @@ -1479,24 +1490,28 @@ run (void *cls) for (size_t i = 0; i < sizeof(p_ah) / sizeof(p_ah[0]); i++) { RND_BLK (&coin_pub); - TALER_blinding_secret_create (&bks); GNUNET_assert (GNUNET_OK == TALER_denom_blind (&dkp->pub, &bks, p_ah[i], &coin_pub, + &alg_values, &c_hash, - &pd.coin_ev, - &pd.coin_ev_size)); - TALER_coin_ev_hash (pd.coin_ev, - pd.coin_ev_size, - &cbc.h_coin_envelope); + &pd.blinded_planchet)); GNUNET_assert (GNUNET_OK == - TALER_denom_sign_blinded (&cbc.sig, - &dkp->priv, - pd.coin_ev, - pd.coin_ev_size)); - GNUNET_free (pd.coin_ev); + TALER_coin_ev_hash (&pd.blinded_planchet, + &cbc.denom_pub_hash, + &cbc.h_coin_envelope)); + GNUNET_assert (GNUNET_OK == + TALER_withdraw_request_hash (&pd.blinded_planchet, + &cbc.denom_pub_hash, + &wih)); GNUNET_assert ( + GNUNET_OK == + TALER_denom_sign_blinded ( + &cbc.sig, + &dkp->priv, + &pd.blinded_planchet)); + TALER_blinded_planchet_free (&pd.blinded_planchet); } } @@ -1505,6 +1520,7 @@ run (void *cls) GNUNET_assert (GNUNET_OK == TALER_amount_set_zero (CURRENCY, &cbc.withdraw_fee)); + { bool found; bool balance_ok; @@ -1513,6 +1529,7 @@ run (void *cls) FAILIF (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != plugin->do_withdraw (plugin->cls, + &wih, &cbc, now, &found, @@ -1534,16 +1551,16 @@ run (void *cls) value.fraction, value.currency)); FAILIF (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != - plugin->get_reserve_by_h_blind (plugin->cls, - &cbc.h_coin_envelope, - &reserve_pub3, - &reserve_out_serial_id)); + plugin->get_reserve_by_wih (plugin->cls, + &wih, + &reserve_pub3, + &reserve_out_serial_id)); FAILIF (0 != GNUNET_memcmp (&reserve_pub, &reserve_pub3)); FAILIF (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != plugin->get_withdraw_info (plugin->cls, - &cbc.h_coin_envelope, + &wih, &cbc2)); FAILIF (0 != GNUNET_memcmp (&cbc2.reserve_sig, &cbc.reserve_sig)); @@ -1558,6 +1575,8 @@ run (void *cls) TALER_denom_sig_unblind (&ds, &cbc2.sig, &bks, + &c_hash, + &alg_values, &dkp->pub)); FAILIF (GNUNET_OK != TALER_denom_pub_verify (&dkp->pub, @@ -1575,6 +1594,8 @@ run (void *cls) TALER_denom_sig_unblind (&deposit.coin.denom_sig, &cbc.sig, &bks, + &c_hash, + &alg_values, &dkp->pub)); deadline = GNUNET_TIME_timestamp_get (); { @@ -1727,6 +1748,8 @@ run (void *cls) { struct TALER_EXCHANGEDB_RefreshRevealedCoin *ccoin; struct GNUNET_TIME_Timestamp now; + struct TALER_BlindedRsaPlanchet *rp; + struct TALER_BlindedPlanchet *bp; now = GNUNET_TIME_timestamp_get (); new_dkp[cnt] = create_denom_key_pair (RSA_KEY_SIZE, @@ -1739,23 +1762,26 @@ run (void *cls) GNUNET_assert (NULL != new_dkp[cnt]); new_denom_pubs[cnt] = new_dkp[cnt]->pub; ccoin = &revealed_coins[cnt]; - ccoin->coin_ev_size = 1 + (size_t) GNUNET_CRYPTO_random_u64 ( + bp = &ccoin->blinded_planchet; + bp->cipher = TALER_DENOMINATION_RSA; + rp = &bp->details.rsa_blinded_planchet; + rp->blinded_msg_size = 1 + (size_t) GNUNET_CRYPTO_random_u64 ( GNUNET_CRYPTO_QUALITY_WEAK, (RSA_KEY_SIZE / 8) - 1); - ccoin->coin_ev = GNUNET_malloc (ccoin->coin_ev_size); + rp->blinded_msg = GNUNET_malloc (rp->blinded_msg_size); GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, - ccoin->coin_ev, - ccoin->coin_ev_size); - GNUNET_CRYPTO_hash (ccoin->coin_ev, - ccoin->coin_ev_size, - &ccoin->coin_envelope_hash.hash); + rp->blinded_msg, + rp->blinded_msg_size); TALER_denom_pub_hash (&new_dkp[cnt]->pub, &ccoin->h_denom_pub); + ccoin->exchange_vals = alg_values; + TALER_coin_ev_hash (bp, + &ccoin->h_denom_pub, + &ccoin->coin_envelope_hash); GNUNET_assert (GNUNET_OK == TALER_denom_sign_blinded (&ccoin->coin_sig, &new_dkp[cnt]->priv, - ccoin->coin_ev, - ccoin->coin_ev_size)); + bp)); } RND_BLK (&tprivs); RND_BLK (&tpub); @@ -1775,11 +1801,13 @@ run (void *cls) { struct TALER_BlindedCoinHash h_coin_ev; struct TALER_CoinSpendPublicKeyP ocp; + struct TALER_DenominationHash denom_hash; - GNUNET_CRYPTO_hash (revealed_coins[0].coin_ev, - revealed_coins[0].coin_ev_size, - &h_coin_ev.hash); - + TALER_denom_pub_hash (&new_denom_pubs[0], + &denom_hash); + TALER_coin_ev_hash (&revealed_coins[0].blinded_planchet, + &denom_hash, + &h_coin_ev); FAILIF (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != plugin->get_old_coin_by_h_blind (plugin->cls, &h_coin_ev, @@ -2154,6 +2182,8 @@ run (void *cls) TALER_denom_sig_unblind (&deposit.coin.denom_sig, &cbc.sig, &bks, + &c_hash, + &alg_values, &dkp->pub)); RND_BLK (&deposit.csig); RND_BLK (&deposit.merchant_pub); @@ -2381,6 +2411,7 @@ drop: rh = NULL; GNUNET_break (GNUNET_OK == plugin->drop_tables (plugin->cls)); +cleanup: if (NULL != dkp) destroy_denom_key_pair (dkp); if (NULL != revealed_coins) @@ -2388,7 +2419,7 @@ drop: for (unsigned int cnt = 0; cnt < MELT_NEW_COINS; cnt++) { TALER_blinded_denom_sig_free (&revealed_coins[cnt].coin_sig); - GNUNET_free (revealed_coins[cnt].coin_ev); + TALER_blinded_planchet_free (&revealed_coins[cnt].blinded_planchet); } GNUNET_free (revealed_coins); revealed_coins = NULL; diff --git a/src/include/taler_auditor_service.h b/src/include/taler_auditor_service.h index f71520345..1d252f9d2 100644 --- a/src/include/taler_auditor_service.h +++ b/src/include/taler_auditor_service.h @@ -259,7 +259,7 @@ TALER_AUDITOR_deposit_confirmation ( const struct TALER_MerchantWireHash *h_wire, const struct TALER_ExtensionContractHash *h_extensions, const struct TALER_PrivateContractHash *h_contract_terms, - struct GNUNET_TIME_Timestamp timestamp, + struct GNUNET_TIME_Timestamp exchange_timestamp, struct GNUNET_TIME_Timestamp wire_deadline, struct GNUNET_TIME_Timestamp refund_deadline, const struct TALER_Amount *amount_without_fee, diff --git a/src/include/taler_crypto_lib.h b/src/include/taler_crypto_lib.h index b755d26b5..9bbf29de4 100644 --- a/src/include/taler_crypto_lib.h +++ b/src/include/taler_crypto_lib.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -27,6 +27,12 @@ #include +/** + * Maximum number of fresh coins we allow per refresh operation. + */ +#define TALER_MAX_FRESH_COINS 256 + + /* ****************** Coin crypto primitives ************* */ GNUNET_NETWORK_STRUCT_BEGIN @@ -44,6 +50,26 @@ struct TALER_SecurityModulePublicKeyP struct GNUNET_CRYPTO_EddsaPublicKey eddsa_pub; }; +/** + * @brief Set of the public keys of the security modules + */ +struct TALER_SecurityModulePublicKeySetP +{ + /** + * Public key of the RSA security module + */ + struct TALER_SecurityModulePublicKeyP rsa; + + /** + * Public key of the CS security module + */ + struct TALER_SecurityModulePublicKeyP cs; + + /** + * Public key of the eddsa security module + */ + struct TALER_SecurityModulePublicKeyP eddsa; +}; /** * @brief Type of private keys for Taler security modules (software or hardware). @@ -345,9 +371,15 @@ struct TALER_CoinSpendSignatureP /** * @brief Type of blinding keys for Taler. + * must be 32 bytes (DB) */ union TALER_DenominationBlindingKeyP { + /** + * Clause Schnorr Signatures have 2 blinding secrets, each containing two unpredictable values. (must be 32 bytes) + */ + struct GNUNET_CRYPTO_CsNonce nonce; + /** * Taler uses RSA for blind signatures. */ @@ -385,7 +417,7 @@ struct TALER_ClaimTokenP * Salt used to hash a merchant's payto:// URI to * compute the "h_wire" (say for deposit requests). */ -struct TALER_WireSalt +struct TALER_WireSaltP { /** * Actual 128-bit salt value. @@ -394,6 +426,20 @@ struct TALER_WireSalt }; +/** + * Hash used to represent an CS public key. Does not include age + * restrictions and is ONLY for CS. Used ONLY for interactions with the CS + * security module. + */ +struct TALER_CsPubHashP +{ + /** + * Actual hash value. + */ + struct GNUNET_HashCode hash; +}; + + /** * Hash used to represent an RSA public key. Does not include age * restrictions and is ONLY for RSA. Used ONLY for interactions with the RSA @@ -409,14 +455,34 @@ struct TALER_RsaPubHashP /** - * Hash @a rsa. - * - * @param rsa key to hash - * @param[out] h_rsa where to write the result + * Master key material for the deriviation of + * private coins and blinding factors during + * withdraw or refresh. */ -void -TALER_rsa_pub_hash (const struct GNUNET_CRYPTO_RsaPublicKey *rsa, - struct TALER_RsaPubHashP *h_rsa); +struct TALER_PlanchetMasterSecretP +{ + + /** + * Key material. + */ + uint32_t key_data[8]; + +}; + + +/** + * Master key material for the deriviation of + * private coins and blinding factors. + */ +struct TALER_RefreshMasterSecretP +{ + + /** + * Key material. + */ + uint32_t key_data[8]; + +}; /** @@ -497,6 +563,22 @@ struct TALER_BlindedCoinHash }; +/** + * Hash used to uniquely represent a withdraw process so as to perform + * idempotency checks (and prevent clients from harmfully replaying withdraw + * operations with problematic variations on the inputs). In the CS case, + * this is a hash over the DK and nonce, while in the RSA case, it is simply a + * hash over the DK and the blinded coin. + */ +struct TALER_WithdrawIdentificationHash +{ + /** + * Actual hash value. + */ + struct GNUNET_HashCode hash; +}; + + /** * Hash used to represent the hash of the public * key of a coin (without blinding). @@ -550,6 +632,27 @@ struct TALER_ExtensionConfigHash GNUNET_NETWORK_STRUCT_END +/** + * Hash @a rsa. + * + * @param rsa key to hash + * @param[out] h_rsa where to write the result + */ +void +TALER_rsa_pub_hash (const struct GNUNET_CRYPTO_RsaPublicKey *rsa, + struct TALER_RsaPubHashP *h_rsa); + +/** + * Hash @a cs. + * + * @param cs key to hash + * @param[out] h_cs where to write the result + */ +void +TALER_cs_pub_hash (const struct GNUNET_CRYPTO_CsPublicKey *cs, + struct TALER_CsPubHashP *h_cs); + + /** * Types of public keys used for denominations in Taler. */ @@ -567,9 +670,9 @@ enum TALER_DenominationCipher TALER_DENOMINATION_RSA = 1, /** - * Clause-Schnorr blind signature. + * Clause Blind Schnorr signature. */ - // TALER_DENOMINATION_CS = 2 + TALER_DENOMINATION_CS = 2 }; @@ -589,6 +692,10 @@ struct TALER_DenominationSignature */ union { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + */ + struct GNUNET_CRYPTO_CsSignature cs_signature; /** * If we use #TALER_DENOMINATION_RSA in @a cipher. @@ -599,6 +706,23 @@ struct TALER_DenominationSignature }; +/** + * The Sign Answer for Clause Blind Schnorr signature. + * The sign operation returns a parameter @param b and the signature + * scalar @param s_scalar. + */ +struct TALER_BlindedDenominationCsSignAnswer +{ + /** + * To make ROS problem harder, the signer chooses an unpredictable b and only calculates signature of c_b + */ + unsigned int b; + + /** + * The blinded s scalar calculated from c_b + */ + struct GNUNET_CRYPTO_CsBlindS s_scalar; +}; /** * @brief Type for *blinded* denomination signatures for Taler. @@ -617,6 +741,12 @@ struct TALER_BlindedDenominationSignature */ union { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + * At this point only the blinded s scalar is used. + * The final signature consisting of r,s is built after unblinding. + */ + struct TALER_BlindedDenominationCsSignAnswer blinded_cs_answer; /** * If we use #TALER_DENOMINATION_RSA in @a cipher. @@ -689,6 +819,10 @@ struct TALER_DenominationPublicKey */ union { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + */ + struct GNUNET_CRYPTO_CsPublicKey cs_public_key; /** * If we use #TALER_DENOMINATION_RSA in @a cipher. @@ -715,6 +849,10 @@ struct TALER_DenominationPrivateKey */ union { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + */ + struct GNUNET_CRYPTO_CsPrivateKey cs_private_key; /** * If we use #TALER_DENOMINATION_RSA in @a cipher. @@ -724,6 +862,100 @@ struct TALER_DenominationPrivateKey } details; }; +/** + * @brief RSA Parameters to create blinded signature + * + */ +struct TALER_BlindedRsaPlanchet +{ + /** + * Blinded message to be signed + * Note: is malloc()'ed! + */ + void *blinded_msg; + + /** + * Size of the @e blinded_msg to be signed. + */ + size_t blinded_msg_size; +}; + + +/** + * Withdraw nonce for CS denominations + */ +struct TALER_CsNonce +{ + /** + * 32 bit nonce to include in withdrawals when using CS. + */ + struct GNUNET_CRYPTO_CsNonce nonce; +}; + + +/** + * @brief CS Parameters to create blinded signature + */ +struct TALER_BlindedCsPlanchet +{ + /** + * The Clause Schnorr c_0 and c_1 containing the blinded message + */ + struct GNUNET_CRYPTO_CsC c[2]; + + /** + * Public nonce. + */ + struct TALER_CsNonce nonce; +}; + + +/** + * @brief Type including Parameters to create blinded signature + */ +struct TALER_BlindedPlanchet +{ + /** + * Type of the sign blinded message + */ + enum TALER_DenominationCipher cipher; + + /** + * Details, depending on @e cipher. + */ + union + { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + */ + struct TALER_BlindedCsPlanchet cs_blinded_planchet; + + /** + * If we use #TALER_DENOMINATION_RSA in @a cipher. + */ + struct TALER_BlindedRsaPlanchet rsa_blinded_planchet; + + } details; +}; + + +/** + * Pair of Public R values for Cs denominations + */ +struct TALER_DenominationCSPublicRPairP +{ + struct GNUNET_CRYPTO_CsRPublic r_pub[2]; +}; + + +/** + * Secret r for Cs denominations + */ +struct TALER_DenominationCSPrivateRPairP +{ + struct GNUNET_CRYPTO_CsRSecret r[2]; +}; + /** * @brief Public information about a coin (including the public key @@ -786,6 +1018,32 @@ struct TALER_TrackTransferDetails }; +/** + * @brief Type of algorithm specific Values for withdrawal + */ +struct TALER_ExchangeWithdrawValues +{ + + /** + * Type of the signature. + */ + enum TALER_DenominationCipher cipher; + + /** + * Details, depending on @e cipher. + */ + union + { + /** + * If we use #TALER_DENOMINATION_CS in @a cipher. + */ + struct TALER_DenominationCSPublicRPairP cs_values; + + } details; + +}; + + /** * Free internals of @a denom_pub, but not @a denom_pub itself. * @@ -796,12 +1054,43 @@ TALER_denom_pub_free (struct TALER_DenominationPublicKey *denom_pub); /** - * Create a blinding secret @a bs for @a cipher. - * - * @param[out] bs blinding secret to initialize + * Create private key for a Taler coin. + * @param ps planchet secret to derive coin priv key + * @param alg_values includes algorithm specific values + * @param[out] coin_priv private key to initialize */ void -TALER_blinding_secret_create (union TALER_DenominationBlindingKeyP *bs); +TALER_planchet_setup_coin_priv ( + const struct TALER_PlanchetMasterSecretP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + struct TALER_CoinSpendPrivateKeyP *coin_priv); + + +/** + * @brief Method to derive withdraw /csr nonce + * + * @param ps planchet secrets of the coin + * @param[out] nonce withdraw nonce included in the request to generate R_0 and R_1 + */ +void +TALER_cs_withdraw_nonce_derive ( + const struct TALER_PlanchetMasterSecretP *ps, + struct TALER_CsNonce *nonce); + + +/** + * @brief Method to derive /csr nonce + * to be used during refresh/melt operation. + * + * @param rms secret input for the refresh operation + * @param idx index of the fresh coin + * @param[out] nonce set to nonce included in the request to generate R_0 and R_1 + */ +void +TALER_cs_refresh_nonce_derive ( + const struct TALER_RefreshMasterSecretP *rms, + uint32_t idx, + struct TALER_CsNonce *nonce); /** @@ -812,9 +1101,9 @@ TALER_blinding_secret_create (union TALER_DenominationBlindingKeyP *bs); * be passed. * * @param[out] denom_priv where to write the private key - * @param[out] deonm_pub where to write the public key + * @param[out] denom_pub where to write the public key * @param cipher which type of cipher to use - * @param ... cipher-specific parameters + * @param ... RSA key size (eg. 2048/3072/4096) * @return #GNUNET_OK on success, #GNUNET_NO if parameters were invalid */ enum GNUNET_GenericReturnValue @@ -845,13 +1134,17 @@ TALER_denom_sig_free (struct TALER_DenominationSignature *denom_sig); /** * Blind coin for blind signing with @a dk using blinding secret @a coin_bks. * + * NOTE: As a particular oddity, the @a blinded_planchet is only partially + * initialized by this function in the case of CS-denominations. Here, the + * 'nonce' must be initialized separately! + * * @param dk denomination public key to blind for * @param coin_bks blinding secret to use * @param age_commitment_hash hash of the age commitment to be used for the coin. NULL if no commitment is made. * @param coin_pub public key of the coin to blind + * @param alg_values algorithm specific values to blind the planchet * @param[out] c_hash resulting hashed coin - * @param[out] coin_ev blinded coin to submit - * @param[out] coin_ev_size number of bytes in @a coin_ev + * @param[out] blinded_planchet planchet data to initialize * @return #GNUNET_OK on success */ enum GNUNET_GenericReturnValue @@ -859,9 +1152,9 @@ TALER_denom_blind (const struct TALER_DenominationPublicKey *dk, const union TALER_DenominationBlindingKeyP *coin_bks, const struct TALER_AgeCommitmentHash *age_commitment_hash, const struct TALER_CoinSpendPublicKeyP *coin_pub, + const struct TALER_ExchangeWithdrawValues *alg_values, struct TALER_CoinPubHash *c_hash, - void **coin_ev, - size_t *coin_ev_size); + struct TALER_BlindedPlanchet *blinded_planchet); /** @@ -869,15 +1162,13 @@ TALER_denom_blind (const struct TALER_DenominationPublicKey *dk, * * @param[out] denom_sig where to write the signature * @param denom_priv private key to use for signing - * @param blinded_msg message to sign - * @param blinded_msg_size number of bytes in @a blinded_msg + * @param blinded_planchet the planchet already blinded * @return #GNUNET_OK on success */ enum GNUNET_GenericReturnValue TALER_denom_sign_blinded (struct TALER_BlindedDenominationSignature *denom_sig, const struct TALER_DenominationPrivateKey *denom_priv, - void *blinded_msg, - size_t blinded_msg_size); + const struct TALER_BlindedPlanchet *blinded_planchet); /** @@ -886,6 +1177,8 @@ TALER_denom_sign_blinded (struct TALER_BlindedDenominationSignature *denom_sig, * @param[out] denom_sig where to write the unblinded signature * @param bdenom_sig the blinded signature * @param bks blinding secret to use + * @param c_hash hash of the coin's public key for verification of the signature + * @param alg_values algorithm specific values * @param denom_pub public key used for signing * @return #GNUNET_OK on success */ @@ -894,6 +1187,8 @@ TALER_denom_sig_unblind ( struct TALER_DenominationSignature *denom_sig, const struct TALER_BlindedDenominationSignature *bdenom_sig, const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinPubHash *c_hash, + const struct TALER_ExchangeWithdrawValues *alg_values, const struct TALER_DenominationPublicKey *denom_pub); @@ -923,7 +1218,7 @@ TALER_denom_pub_hash (const struct TALER_DenominationPublicKey *denom_pub, * @a denom_dst. * * @param[out] denom_dst target to copy to - * @param denom_str public key to copy + * @param denom_src public key to copy */ void TALER_denom_pub_deep_copy (struct TALER_DenominationPublicKey *denom_dst, @@ -935,7 +1230,7 @@ TALER_denom_pub_deep_copy (struct TALER_DenominationPublicKey *denom_dst, * @a denom_dst. * * @param[out] denom_dst target to copy to - * @param denom_str public key to copy + * @param denom_src public key to copy */ void TALER_denom_sig_deep_copy (struct TALER_DenominationSignature *denom_dst, @@ -947,7 +1242,7 @@ TALER_denom_sig_deep_copy (struct TALER_DenominationSignature *denom_dst, * @a denom_dst. * * @param[out] denom_dst target to copy to - * @param denom_str public key to copy + * @param denom_src public key to copy */ void TALER_blinded_denom_sig_deep_copy ( @@ -992,6 +1287,19 @@ TALER_blinded_denom_sig_cmp ( const struct TALER_BlindedDenominationSignature *sig2); +/** + * Compare two blinded planchets. + * + * @param bp1 first blinded planchet + * @param bp2 second blinded planchet + * @return 0 if the keys are equal, otherwise -1 or 1 + */ +int +TALER_blinded_planchet_cmp ( + const struct TALER_BlindedPlanchet *bp1, + const struct TALER_BlindedPlanchet *bp2); + + /** * Obtain denomination public key from a denomination private key. * @@ -1038,16 +1346,33 @@ TALER_test_coin_valid (const struct TALER_CoinPublicInfo *coin_public_info, /** * Compute the hash of a blinded coin. * - * @param coin_ev blinded coin - * @param coin_ev_size number of bytes in @a coin_ev + * @param blinded_planchet blinded planchet + * @param denom_hash hash of the denomination publick key * @param[out] bch where to write the hash + * @return #GNUNET_OK when successful, #GNUNET_SYSERR if an internal error occured */ -void -TALER_coin_ev_hash (const void *coin_ev, - size_t coin_ev_size, +enum GNUNET_GenericReturnValue +TALER_coin_ev_hash (const struct TALER_BlindedPlanchet *blinded_planchet, + const struct TALER_DenominationHash *denom_hash, struct TALER_BlindedCoinHash *bch); +/** + * Compute the hash to uniquely identify a withdraw + * request. + * + * @param blinded_planchet blinded planchet + * @param denom_hash hash of the denomination publick key + * @param[out] wih where to write the hash + * @return #GNUNET_OK when successful, #GNUNET_SYSERR if an internal error occured + */ +enum GNUNET_GenericReturnValue +TALER_withdraw_request_hash ( + const struct TALER_BlindedPlanchet *blinded_planchet, + const struct TALER_DenominationHash *denom_hash, + struct TALER_WithdrawIdentificationHash *wih); + + /** * Compute the hash of a coin. * @@ -1071,34 +1396,6 @@ void TALER_payto_hash (const char *payto, struct TALER_PaytoHash *h_payto); - -GNUNET_NETWORK_STRUCT_BEGIN - -/** - * Header for serializations of coin-specific information about the - * fresh coins we generate. These are the secrets that arise during - * planchet generation, which is the first stage of creating a new - * coin. - */ -struct TALER_PlanchetSecretsP -{ - - /** - * Private key of the coin. - */ - struct TALER_CoinSpendPrivateKeyP coin_priv; - - /** - * The blinding key. - */ - union TALER_DenominationBlindingKeyP blinding_key; - -}; - - -GNUNET_NETWORK_STRUCT_END - - /** * Details about a planchet that the customer wants to obtain * a withdrawal authorization. This is the information that @@ -1113,14 +1410,9 @@ struct TALER_PlanchetDetail struct TALER_DenominationHash denom_pub_hash; /** - * Blinded coin (see GNUNET_CRYPTO_rsa_blind()). Note: is malloc()'ed! + * The blinded planchet */ - void *coin_ev; - - /** - * Number of bytes in @a coin_ev. - */ - size_t coin_ev_size; + struct TALER_BlindedPlanchet blinded_planchet; }; @@ -1238,57 +1530,128 @@ GNUNET_NETWORK_STRUCT_END /** - * Setup information for a fresh coin, deriving the coin private key - * and the blinding factor from the @a secret_seed with a KDF salted - * by the @a coin_num_salt. + * Setup information for a fresh coin, deriving the coin planchet secrets from + * which we will later derive the private key and the blinding factor. The + * planchet secrets derivation is based on the @a secret_seed with a KDF + * salted by the @a coin_num_salt. * * @param secret_seed seed to use for KDF to derive coin keys * @param coin_num_salt number of the coin to include in KDF * @param[out] ps value to initialize */ void -TALER_planchet_setup_refresh (const struct TALER_TransferSecretP *secret_seed, - uint32_t coin_num_salt, - struct TALER_PlanchetSecretsP *ps); +TALER_transfer_secret_to_planchet_secret ( + const struct TALER_TransferSecretP *secret_seed, + uint32_t coin_num_salt, + struct TALER_PlanchetMasterSecretP *ps); /** - * Setup information for a fresh coin. + * Derive the @a coin_num transfer private key @a tpriv from a refresh from + * the @a rms seed of the refresh operation. The transfer private key + * derivation is based on the @a ps with a KDF salted by the @a coin_num. + * + * @param rms seed to use for KDF to derive transfer keys + * @param cnc_num cut and choose number to include in KDF + * @param[out] tpriv value to initialize + */ +void +TALER_planchet_secret_to_transfer_priv ( + const struct TALER_RefreshMasterSecretP *rms, + uint32_t cnc_num, + struct TALER_TransferPrivateKeyP *tpriv); + + +/** + * Setup secret seed information for fresh coins to be + * withdrawn. * * @param[out] ps value to initialize */ void -TALER_planchet_setup_random (struct TALER_PlanchetSecretsP *ps); +TALER_planchet_master_setup_random ( + struct TALER_PlanchetMasterSecretP *ps); /** - * Prepare a planchet for tipping. Creates and blinds a coin. + * Setup secret seed for fresh coins to be refreshed. + * + * @param[out] rms value to initialize + */ +void +TALER_refresh_master_setup_random ( + struct TALER_RefreshMasterSecretP *rms); + + +/** + * Create a blinding secret @a bks given the client's @a ps and the alg_values + * from the exchange. + * + * @param ps secret to derive blindings from + * @param alg_values withdraw values containing cipher and additional CS values + * @param[out] bks blinding secrets + */ +void +TALER_planchet_blinding_secret_create ( + const struct TALER_PlanchetMasterSecretP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + union TALER_DenominationBlindingKeyP *bks); + + +/** + * Prepare a planchet for withdrawal. Creates and blinds a coin. * * @param dk denomination key for the coin to be created - * @param ps secret planchet internals (for #TALER_planchet_to_coin) - * @param ach (optional) hash of age commitment to bind to this coin, maybe NULL + * @param alg_values algorithm specific values + * @param bks blinding secrets + * @param coin_priv coin private key + * @param ach hash of age commitment to bind to this coin, maybe NULL * @param[out] c_hash set to the hash of the public key of the coin (needed later) * @param[out] pd set to the planchet detail for TALER_MERCHANT_tip_pickup() and - * other withdraw operations + * other withdraw operations, `pd->blinded_planchet.cipher` will be set + * to cipher from @a dk * @return #GNUNET_OK on success */ enum GNUNET_GenericReturnValue TALER_planchet_prepare (const struct TALER_DenominationPublicKey *dk, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinSpendPrivateKeyP *coin_priv, const struct TALER_AgeCommitmentHash *ach, struct TALER_CoinPubHash *c_hash, struct TALER_PlanchetDetail *pd); +/** + * Frees blinded message inside blinded planchet depending on `blinded_planchet->cipher`. + * Does not free the @a blinded_planchet itself! + * + * @param[in] blinded_planchet blinded planchet + */ +void +TALER_blinded_planchet_free (struct TALER_BlindedPlanchet *blinded_planchet); + + +/** + * Frees blinded message inside planchet detail @a pd. + * + * @param[in] pd planchet detail to free + */ +void +TALER_planchet_detail_free (struct TALER_PlanchetDetail *pd); + + /** * Obtain a coin from the planchet's secrets and the blind signature * of the exchange. * * @param dk denomination key, must match what was given to #TALER_planchet_prepare() * @param blind_sig blind signature from the exchange - * @param ps secrets from #TALER_planchet_prepare() - * @param ach (optional) hash of age commitment that is bound to this coin, maybe NULL + * @param bks blinding key secret + * @param coin_priv private key of the coin + * @param ach hash of age commitment that is bound to this coin, maybe NULL * @param c_hash hash of the coin's public key for verification of the signature + * @param alg_values values obtained from the exchange for the withdrawal * @param[out] coin set to the details of the fresh coin * @return #GNUNET_OK on success */ @@ -1296,13 +1659,24 @@ enum GNUNET_GenericReturnValue TALER_planchet_to_coin ( const struct TALER_DenominationPublicKey *dk, const struct TALER_BlindedDenominationSignature *blind_sig, - const struct TALER_PlanchetSecretsP *ps, + const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinSpendPrivateKeyP *coin_priv, const struct TALER_AgeCommitmentHash *ach, const struct TALER_CoinPubHash *c_hash, + const struct TALER_ExchangeWithdrawValues *alg_values, struct TALER_FreshCoin *coin); -/* ****************** Refresh crypto primitives ************* */ +/** + * Add the hash of the @a bp (in some canonicalized form) + * to the @a hash_context. + * + * @param bp blinded planchet to hash + * @param[in,out] hash_context hash context to use + */ +void +TALER_blinded_planchet_hash (const struct TALER_BlindedPlanchet *bp, + struct GNUNET_HashContext *hash_context); /** @@ -1365,14 +1739,9 @@ struct TALER_RefreshCoinData const struct TALER_DenominationPublicKey *dk; /** - * The envelope with the blinded coin. + * The blinded planchet (details depend on cipher). */ - void *coin_ev; - - /** - * Number of bytes in @a coin_ev - */ - size_t coin_ev_size; + struct TALER_BlindedPlanchet blinded_planchet; }; @@ -1492,21 +1861,20 @@ TALER_CRYPTO_helper_rsa_poll (struct TALER_CRYPTO_RsaDenominationHelper *dh); * @param h_rsa hash of the RSA public key to use to sign * @param msg message to sign * @param msg_size number of bytes in @a msg - * @param[out] ec set to the error code (or #TALER_EC_NONE on success) - * @return signature, the value inside the structure will be NULL on failure, - * see @a ec for details about the failure + * @param[out] bs set to the blind signature + * @return #TALER_EC_NONE on success */ -struct TALER_BlindedDenominationSignature +enum TALER_ErrorCode TALER_CRYPTO_helper_rsa_sign ( struct TALER_CRYPTO_RsaDenominationHelper *dh, const struct TALER_RsaPubHashP *h_rsa, const void *msg, size_t msg_size, - enum TALER_ErrorCode *ec); + struct TALER_BlindedDenominationSignature *bs); /** - * Ask the helper to revoke the public key associated with @param h_denom_pub . + * Ask the helper to revoke the public key associated with @a h_denom_pub. * Will cause the helper to tell all clients that the key is now unavailable, * and to create a replacement key. * @@ -1535,6 +1903,147 @@ void TALER_CRYPTO_helper_rsa_disconnect ( struct TALER_CRYPTO_RsaDenominationHelper *dh); +/* **************** Helper-based CS operations **************** */ + +/** + * Handle for talking to an Denomination key signing helper. + */ +struct TALER_CRYPTO_CsDenominationHelper; + +/** + * Function called with information about available keys for signing. Usually + * only called once per key upon connect. Also called again in case a key is + * being revoked, in that case with an @a end_time of zero. + * + * @param cls closure + * @param section_name name of the denomination type in the configuration; + * NULL if the key has been revoked or purged + * @param start_time when does the key become available for signing; + * zero if the key has been revoked or purged + * @param validity_duration how long does the key remain available for signing; + * zero if the key has been revoked or purged + * @param h_cs hash of the CS @a denom_pub that is available (or was purged) + * @param denom_pub the public key itself, NULL if the key was revoked or purged + * @param sm_pub public key of the security module, NULL if the key was revoked or purged + * @param sm_sig signature from the security module, NULL if the key was revoked or purged + * The signature was already verified against @a sm_pub. + */ +typedef void +(*TALER_CRYPTO_CsDenominationKeyStatusCallback)( + void *cls, + const char *section_name, + struct GNUNET_TIME_Timestamp start_time, + struct GNUNET_TIME_Relative validity_duration, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_DenominationPublicKey *denom_pub, + const struct TALER_SecurityModulePublicKeyP *sm_pub, + const struct TALER_SecurityModuleSignatureP *sm_sig); + + +/** + * Initiate connection to an denomination key helper. + * + * @param cfg configuration to use + * @param dkc function to call with key information + * @param dkc_cls closure for @a dkc + * @return NULL on error (such as bad @a cfg). + */ +struct TALER_CRYPTO_CsDenominationHelper * +TALER_CRYPTO_helper_cs_connect ( + const struct GNUNET_CONFIGURATION_Handle *cfg, + TALER_CRYPTO_CsDenominationKeyStatusCallback dkc, + void *dkc_cls); + + +/** + * Function to call to 'poll' for updates to the available key material. + * Should be called whenever it is important that the key material status is + * current, like when handling a "/keys" request. This function basically + * briefly checks if there are messages from the helper announcing changes to + * denomination keys. + * + * @param dh helper process connection + */ +void +TALER_CRYPTO_helper_cs_poll (struct TALER_CRYPTO_CsDenominationHelper *dh); + + +/** + * Request helper @a dh to sign @a msg using the public key corresponding to + * @a h_denom_pub. + * + * This operation will block until the signature has been obtained. Should + * this process receive a signal (that is not ignored) while the operation is + * pending, the operation will fail. Note that the helper may still believe + * that it created the signature. Thus, signals may result in a small + * differences in the signature counters. Retrying in this case may work. + * + * @param dh helper process connection + * @param h_cs hash of the CS public key to use to sign + * @param blinded_planchet blinded planchet containing c and nonce + * @param[out] bs set to the blind signature + * @return #TALER_EC_NONE on success + */ +enum TALER_ErrorCode +TALER_CRYPTO_helper_cs_sign ( + struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_BlindedCsPlanchet *blinded_planchet, + struct TALER_BlindedDenominationSignature *bs); + + +/** + * Ask the helper to revoke the public key associated with @a h_cs. + * Will cause the helper to tell all clients that the key is now unavailable, + * and to create a replacement key. + * + * This operation will block until the revocation request has been + * transmitted. Should this process receive a signal (that is not ignored) + * while the operation is pending, the operation may fail. If the key is + * unknown, this function will also appear to have succeeded. To be sure that + * the revocation worked, clients must watch the denomination key status + * callback. + * + * @param dh helper to process connection + * @param h_cs hash of the CS public key to revoke + */ +void +TALER_CRYPTO_helper_cs_revoke ( + struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs); + + +/** + * Ask the helper to derive R using the @a nonce and denomination key + * associated with @a h_cs. + * + * This operation will block until the R has been obtained. Should + * this process receive a signal (that is not ignored) while the operation is + * pending, the operation will fail. Note that the helper may still believe + * that it created the signature. Thus, signals may result in a small + * differences in the signature counters. Retrying in this case may work. + * + * @param dh helper to process connection + * @param h_cs hash of the CS public key to revoke + * @param nonce witdhraw nonce + * @param[out] crp set to the pair of R values + * @return set to the error code (or #TALER_EC_NONE on success) + */ +enum TALER_ErrorCode +TALER_CRYPTO_helper_cs_r_derive (struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_CsNonce *nonce, + struct TALER_DenominationCSPublicRPairP *crp); + + +/** + * Close connection to @a dh. + * + * @param[in] dh connection to close + */ +void +TALER_CRYPTO_helper_cs_disconnect ( + struct TALER_CRYPTO_CsDenominationHelper *dh); /** * Handle for talking to an online key signing helper. @@ -1647,7 +2156,7 @@ TALER_CRYPTO_helper_esign_sign_ ( /** - * Ask the helper to revoke the public key @param exchange_pub . + * Ask the helper to revoke the public key @a exchange_pub . * Will cause the helper to tell all clients that the key is now unavailable, * and to create a replacement key. * @@ -1712,6 +2221,17 @@ TALER_exchange_deposit_confirm_verify ( /* ********************* wallet signing ************************** */ +/** + * Sign a request by a wallet to perform a KYC check. + * + * @param reserve_priv key identifying the wallet/account + * @param reserve_sig resulting signature + */ +void +TALER_wallet_account_setup_sign ( + const struct TALER_ReservePrivateKeyP *reserve_priv, + struct TALER_ReserveSignatureP *reserve_sig); + /** * Sign a deposit permission. Function for wallets. @@ -1781,7 +2301,7 @@ TALER_wallet_deposit_verify ( /** * Sign a melt request. * - * @param amount the amount to be melted (with fee) + * @param amount_with_fee the amount to be melted (with fee) * @param melt_fee the melt fee we expect to pay * @param rc refresh session we are committed to * @param h_denom_pub hash of the coin denomination's public key @@ -1801,7 +2321,7 @@ TALER_wallet_melt_sign ( /** * Verify a melt request. * - * @param amount the amount to be melted (with fee) + * @param amount_with_fee the amount to be melted (with fee) * @param melt_fee the melt fee we expect to pay * @param rc refresh session we are committed to * @param h_denom_pub hash of the coin denomination's public key @@ -1826,16 +2346,14 @@ TALER_wallet_melt_verify ( * * @param h_denom_pub hash of the denomiantion public key of the new coin * @param transfer_pub transfer public key - * @param coin_ev coin envelope - * @param coin_ev_size number of bytes in @a coin_ev + * @param bch blinded coin hash * @param old_coin_priv private key to sign with * @param[out] coin_sig resulting signature */ void TALER_wallet_link_sign (const struct TALER_DenominationHash *h_denom_pub, const struct TALER_TransferPublicKeyP *transfer_pub, - const void *coin_ev, - size_t coin_ev_size, + const struct TALER_BlindedCoinHash *bch, const struct TALER_CoinSpendPrivateKeyP *old_coin_priv, struct TALER_CoinSpendSignatureP *coin_sig); @@ -1862,22 +2380,57 @@ TALER_wallet_link_verify ( /** - * Sign link data. + * Sign withdraw request. * - * @param h_denom_pub hash of the denomiantion public key of the new coin - * @param transfer_pub transfer public key - * @param coin_ev coin envelope - * @param coin_ev_size number of bytes in @a coin_ev - * @param old_coin_priv private key to sign with - * @param[out] coin_sig resulting signature + * @param h_denom_pub hash of the denomiantion public key of the coin to withdraw + * @param amount_with_fee amount to debit the reserve for + * @param bch blinded coin hash + * @param reserve_priv private key to sign with + * @param[out] reserve_sig resulting signature */ void -TALER_wallet_link_sign (const struct TALER_DenominationHash *h_denom_pub, - const struct TALER_TransferPublicKeyP *transfer_pub, - const void *coin_ev, - size_t coin_ev_size, - const struct TALER_CoinSpendPrivateKeyP *old_coin_priv, - struct TALER_CoinSpendSignatureP *coin_sig); +TALER_wallet_withdraw_sign ( + const struct TALER_DenominationHash *h_denom_pub, + const struct TALER_Amount *amount_with_fee, + const struct TALER_BlindedCoinHash *bch, + const struct TALER_ReservePrivateKeyP *reserve_priv, + struct TALER_ReserveSignatureP *reserve_sig); + + +/** + * Verify withdraw request. + * + * @param h_denom_pub hash of the denomiantion public key of the coin to withdraw + * @param amount_with_fee amount to debit the reserve for + * @param bch blinded coin hash + * @param reserve_pub public key of the reserve + * @param reserve_sig resulting signature + * @return #GNUNET_OK if the signature is valid + */ +enum GNUNET_GenericReturnValue +TALER_wallet_withdraw_verify ( + const struct TALER_DenominationHash *h_denom_pub, + const struct TALER_Amount *amount_with_fee, + const struct TALER_BlindedCoinHash *bch, + const struct TALER_ReservePublicKeyP *reserve_pub, + const struct TALER_ReserveSignatureP *reserve_sig); + + +/** + * Verify exchange melt confirmation. + * + * @param rc refresh session this is about + * @param noreveal_index gamma value chosen by the exchange + * @param exchange_pub public signing key used + * @param exchange_sig signature to check + * @return #GNUNET_OK if the signature is valid + */ +enum GNUNET_GenericReturnValue +TALER_exchange_melt_confirmation_verify ( + const struct TALER_RefreshCommitmentP *rc, + uint32_t noreveal_index, + const struct TALER_ExchangePublicKeyP *exchange_pub, + const struct TALER_ExchangeSignatureP *exchange_sig); /** @@ -1902,7 +2455,6 @@ TALER_wallet_recoup_verify ( * * @param h_denom_pub hash of the denomiantion public key of the coin * @param coin_bks blinding factor used when withdrawing the coin - * @param requested_amount amount that is left to be recouped * @param coin_priv coin key of the coin to be recouped * @param coin_sig resulting signature */ @@ -1936,7 +2488,6 @@ TALER_wallet_recoup_refresh_verify ( * * @param h_denom_pub hash of the denomiantion public key of the coin * @param coin_bks blinding factor used when withdrawing the coin - * @param requested_amount amount that is left to be recouped * @param coin_priv coin key of the coin to be recouped * @param coin_sig resulting signature */ @@ -2307,6 +2858,47 @@ TALER_exchange_secmod_rsa_verify ( const struct TALER_SecurityModuleSignatureP *secm_sig); +/** + * Create security module denomination signature. + * + * @param h_cs hash of the CS public key to sign + * @param section_name name of the section in the configuration + * @param start_sign starting point of validity for signing + * @param duration how long will the key be in use + * @param secm_priv security module key to sign with + * @param[out] secm_sig where to write the signature + */ +void +TALER_exchange_secmod_cs_sign ( + const struct TALER_CsPubHashP *h_cs, + const char *section_name, + struct GNUNET_TIME_Timestamp start_sign, + struct GNUNET_TIME_Relative duration, + const struct TALER_SecurityModulePrivateKeyP *secm_priv, + struct TALER_SecurityModuleSignatureP *secm_sig); + + +/** + * Verify security module denomination signature. + * + * @param h_cs hash of the public key to validate + * @param section_name name of the section in the configuration + * @param start_sign starting point of validity for signing + * @param duration how long will the key be in use + * @param secm_pub public key to verify against + * @param secm_sig the signature the signature + * @return #GNUNET_OK if the signature is valid + */ +enum GNUNET_GenericReturnValue +TALER_exchange_secmod_cs_verify ( + const struct TALER_CsPubHashP *h_cs, + const char *section_name, + struct GNUNET_TIME_Timestamp start_sign, + struct GNUNET_TIME_Relative duration, + const struct TALER_SecurityModulePublicKeyP *secm_pub, + const struct TALER_SecurityModuleSignatureP *secm_sig); + + /** * Create denomination key validity signature by the auditor. * @@ -2534,7 +3126,7 @@ TALER_exchange_wire_signature_make ( */ void TALER_merchant_wire_signature_hash (const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, struct TALER_MerchantWireHash *hc); @@ -2550,7 +3142,7 @@ TALER_merchant_wire_signature_hash (const char *payto_uri, enum GNUNET_GenericReturnValue TALER_merchant_wire_signature_check ( const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, const struct TALER_MerchantPublicKeyP *merch_pub, const struct TALER_MerchantSignatureP *merch_sig); @@ -2566,7 +3158,7 @@ TALER_merchant_wire_signature_check ( void TALER_merchant_wire_signature_make ( const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, const struct TALER_MerchantPrivateKeyP *merch_priv, struct TALER_MerchantSignatureP *merch_sig); diff --git a/src/include/taler_exchange_service.h b/src/include/taler_exchange_service.h index 8e361e5ec..fef09f721 100644 --- a/src/include/taler_exchange_service.h +++ b/src/include/taler_exchange_service.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software @@ -919,7 +919,7 @@ TALER_EXCHANGE_deposit ( const struct TALER_Amount *amount, struct GNUNET_TIME_Timestamp wire_deadline, const char *merchant_payto_uri, - const struct TALER_WireSalt *wire_salt, + const struct TALER_WireSaltP *wire_salt, const struct TALER_PrivateContractHash *h_contract_terms, const struct TALER_AgeCommitmentHash *h_age_commitment, const json_t *extension_details, @@ -1031,6 +1031,119 @@ void TALER_EXCHANGE_refund_cancel (struct TALER_EXCHANGE_RefundHandle *refund); +/* ********************* POST /csr *********************** */ + + +/** + * @brief A /csr Handle + */ +struct TALER_EXCHANGE_CsRHandle; + + +/** + * Details about a response for a CS R request. + */ +struct TALER_EXCHANGE_CsRResponse +{ + /** + * HTTP response data. + */ + struct TALER_EXCHANGE_HttpResponse hr; + + /** + * Details about the response. + */ + union + { + /** + * Details if the status is #MHD_HTTP_OK. + */ + struct + { + /** + * Length of the @e alg_values array. + */ + unsigned int alg_values_len; + + /** + * Values contributed by the exchange for the + * respective coin's withdraw operation. + */ + const struct TALER_ExchangeWithdrawValues *alg_values; + } success; + + /** + * Details if the status is #MHD_HTTP_GONE. + */ + struct + { + /* TODO: returning full details is not implemented */ + } gone; + + } details; +}; + + +/** + * Callbacks of this type are used to serve the result of submitting a + * CS R request to a exchange. + * + * @param cls closure + * @param csrr response details + */ +typedef void +(*TALER_EXCHANGE_CsRCallback) (void *cls, + const struct TALER_EXCHANGE_CsRResponse *csrr); + + +/** + * Information we pass per coin to a /csr request. + */ +struct TALER_EXCHANGE_NonceKey +{ + /** + * Which denomination key is the /csr request for? + */ + const struct TALER_EXCHANGE_DenomPublicKey *pk; + + /** + * What is the client nonce for the request? + */ + struct TALER_CsNonce nonce; +}; + + +/** + * Get a CS R using a /csr request. + * + * @param exchange the exchange handle; the exchange must be ready to operate + * @param nks_len length of the @a nks array + * @param nks array of denominations and nonces + * @param res_cb the callback to call when the final result for this request is available + * @param res_cb_cls closure for the above callback + * @return handle for the operation on success, NULL on error, i.e. + * if the inputs are invalid (i.e. denomination key not with this exchange). + * In this case, the callback is not called. + */ +struct TALER_EXCHANGE_CsRHandle * +TALER_EXCHANGE_csr (struct TALER_EXCHANGE_Handle *exchange, + unsigned int nks_len, + struct TALER_EXCHANGE_NonceKey *nks, + TALER_EXCHANGE_CsRCallback res_cb, + void *res_cb_cls); + + +/** + * + * Cancel a CS R request. This function cannot be used + * on a request handle if a response is already served for it. + * + * @param csrh the withdraw handle + */ +void +TALER_EXCHANGE_csr_cancel (struct TALER_EXCHANGE_CsRHandle *csrh); + + /* ********************* GET /reserves/$RESERVE_PUB *********************** */ @@ -1271,6 +1384,36 @@ TALER_EXCHANGE_reserves_get_cancel ( struct TALER_EXCHANGE_WithdrawHandle; +/** + * All the details about a coin that are generated during withdrawal and that + * may be needed for future operations on the coin. + */ +struct TALER_EXCHANGE_PrivateCoinDetails +{ + /** + * Private key of the coin. + */ + struct TALER_CoinSpendPrivateKeyP coin_priv; + + /** + * Value used to blind the key for the signature. + * Needed for recoup operations. + */ + union TALER_DenominationBlindingKeyP bks; + + /** + * Signature over the coin. + */ + struct TALER_DenominationSignature sig; + + /** + * Values contributed from the exchange during the + * withdraw protocol. + */ + struct TALER_ExchangeWithdrawValues exchange_vals; +}; + + /** * Details about a response for a withdraw request. */ @@ -1289,13 +1432,7 @@ struct TALER_EXCHANGE_WithdrawResponse /** * Details if the status is #MHD_HTTP_OK. */ - struct - { - /** - * Signature over the coin. - */ - struct TALER_DenominationSignature sig; - } success; + struct TALER_EXCHANGE_PrivateCoinDetails success; /** * Details if the status is #MHD_HTTP_ACCEPTED. @@ -1357,7 +1494,7 @@ typedef void * @param reserve_priv private key of the reserve to withdraw from * @param ps secrets of the planchet * caller must have committed this value to disk before the call (with @a pk) - * @param ach (optional) hash of the age commitment that should be bound to this coin. Maybe NULL. + * @param ach hash of the age commitment that should be bound to this coin. Maybe NULL. * @param res_cb the callback to call when the final result for this request is available * @param res_cb_cls closure for @a res_cb * @return NULL @@ -1369,7 +1506,7 @@ TALER_EXCHANGE_withdraw ( struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_ReservePrivateKeyP *reserve_priv, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_PlanchetMasterSecretP *ps, const struct TALER_AgeCommitmentHash *ach, TALER_EXCHANGE_WithdrawCallback res_cb, void *res_cb_cls); @@ -1451,53 +1588,45 @@ TALER_EXCHANGE_withdraw2_cancel (struct TALER_EXCHANGE_Withdraw2Handle *wh); /** - * Melt (partially spent) coins to obtain fresh coins that are - * unlinkable to the original coin(s). Note that melting more - * than one coin in a single request will make those coins linkable, - * so the safest operation only melts one coin at a time. - * - * This API is typically used by a wallet. Note that to ensure that - * no money is lost in case of hardware failures, is operation does - * not actually initiate the request. Instead, it generates a buffer - * which the caller must store before proceeding with the actual call - * to #TALER_EXCHANGE_melt() that will generate the request. - * - * This function does verify that the given request data is internally - * consistent. However, the @a melts_sigs are NOT verified. - * - * Aside from some non-trivial cryptographic operations that might - * take a bit of CPU time to complete, this function returns - * its result immediately and does not start any asynchronous - * processing. This function is also thread-safe. - * - * @param melt_priv private keys of the coin to melt - * @param melt_amount amount specifying how much - * the coin will contribute to the melt (including fee) - * @param melt_sig signatures affirming the - * validity of the public keys corresponding to the - * @a melt_priv private key - * @param melt_pk denomination key information - * record corresponding to the @a melt_sig - * validity of the keys - * @param age_commitment (optional) age commitment that went into the original - * coin. Maybe NULL, if no age commitment was provided. - * @param fresh_pks_len length of the @a pks array - * @param fresh_pks array of @a pks_len denominations of fresh coins to create - * @return NULL - * if the inputs are invalid (i.e. denomination key not with this exchange). - * Otherwise, JSON data structure to store persistently - * before proceeding to #TALER_EXCHANGE_melt(). - * Non-null results should be freed using GNUNET_free(). + * Information needed to melt (partially spent) coins to obtain fresh coins + * that are unlinkable to the original coin(s). Note that melting more than + * one coin in a single request will make those coins linkable, so we only melt one coin at a time. */ -json_t * -TALER_EXCHANGE_refresh_prepare ( - const struct TALER_CoinSpendPrivateKeyP *melt_priv, - const struct TALER_Amount *melt_amount, - const struct TALER_DenominationSignature *melt_sig, - const struct TALER_EXCHANGE_DenomPublicKey *melt_pk, - const struct TALER_AgeCommitment *age_commitment, - unsigned int fresh_pks_len, - const struct TALER_EXCHANGE_DenomPublicKey *fresh_pks); +struct TALER_EXCHANGE_RefreshData +{ + /** + * private key of the coin to melt + */ + struct TALER_CoinSpendPrivateKeyP melt_priv; + + /** + * amount specifying how much the coin will contribute to the melt + * (including fee) + */ + struct TALER_Amount melt_amount; + + /** + * signatures affirming the validity of the public keys corresponding to the + * @e melt_priv private key + */ + struct TALER_DenominationSignature melt_sig; + + /** + * denomination key information record corresponding to the @e melt_sig + * validity of the keys + */ + struct TALER_EXCHANGE_DenomPublicKey melt_pk; + + /** + * array of @e pks_len denominations of fresh coins to create + */ + const struct TALER_EXCHANGE_DenomPublicKey *fresh_pks; + + /** + * length of the @e pks array + */ + unsigned int fresh_pks_len; +}; /* ********************* /coins/$COIN_PUB/melt ***************************** */ @@ -1508,6 +1637,67 @@ TALER_EXCHANGE_refresh_prepare ( struct TALER_EXCHANGE_MeltHandle; +/** + * Information we obtain per coin during melting. + */ +struct TALER_EXCHANGE_MeltBlindingDetail +{ + /** + * Exchange values contributed to the refresh operation + */ + struct TALER_ExchangeWithdrawValues alg_value; + +}; + + +/** + * Response returned to a /melt request. + */ +struct TALER_EXCHANGE_MeltResponse +{ + /** + * Full HTTP response details. + */ + struct TALER_EXCHANGE_HttpResponse hr; + + /** + * Parsed response details, variant depending on the + * @e hr.http_status. + */ + union + { + /** + * Results for status #MHD_HTTP_SUCCESS. + */ + struct + { + + /** + * Information returned per coin. + */ + const struct TALER_EXCHANGE_MeltBlindingDetail *mbds; + + /** + * Key used by the exchange to sign the response. + */ + struct TALER_ExchangePublicKeyP sign_key; + + /** + * Length of the @a mbds array with the exchange values + * and blinding keys we are using. + */ + unsigned int num_mbds; + + /** + * Gamma value chosen by the exchange. + */ + uint32_t noreveal_index; + } success; + + } details; +}; + + /** * Callbacks of this type are used to notify the application about the result * of the /coins/$COIN_PUB/melt stage. If successful, the @a noreveal_index @@ -1515,17 +1705,12 @@ struct TALER_EXCHANGE_MeltHandle; * #TALER_EXCHANGE_refreshes_reveal(). * * @param cls closure - * @param hr HTTP response data - * @param noreveal_index choice by the exchange in the cut-and-choose protocol, - * UINT32_MAX on error - * @param sign_key exchange key used to sign @a full_response, or NULL + * @param mr response details */ typedef void (*TALER_EXCHANGE_MeltCallback) ( void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - uint32_t noreveal_index, - const struct TALER_ExchangePublicKeyP *sign_key); + const struct TALER_EXCHANGE_MeltResponse *mr); /** @@ -1534,13 +1719,12 @@ typedef void * * This API is typically used by a wallet. Note that to ensure that * no money is lost in case of hardware failures, the provided - * argument should have been constructed using - * #TALER_EXCHANGE_refresh_prepare and committed to persistent storage + * argument @a rd should be committed to persistent storage * prior to calling this function. * * @param exchange the exchange handle; the exchange must be ready to operate - * @param refresh_data the refresh data as returned from - #TALER_EXCHANGE_refresh_prepare()) + * @param rms the fresh secret that defines the refresh operation + * @param rd the refresh data specifying the characteristics of the operation * @param melt_cb the callback to call with the result * @param melt_cb_cls closure for @a melt_cb * @return a handle for this request; NULL if the argument was invalid. @@ -1548,7 +1732,8 @@ typedef void */ struct TALER_EXCHANGE_MeltHandle * TALER_EXCHANGE_melt (struct TALER_EXCHANGE_Handle *exchange, - const json_t *refresh_data, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, TALER_EXCHANGE_MeltCallback melt_cb, void *melt_cb_cls); @@ -1566,27 +1751,87 @@ TALER_EXCHANGE_melt_cancel (struct TALER_EXCHANGE_MeltHandle *mh); /* ********************* /refreshes/$RCH/reveal ***************************** */ +/** + * Information about a coin obtained via /refreshes/$RCH/reveal. + */ +struct TALER_EXCHANGE_RevealedCoinInfo +{ + /** + * Private key of the coin. + */ + struct TALER_CoinSpendPrivateKeyP coin_priv; + + /** + * Master secret of this coin. + */ + struct TALER_PlanchetMasterSecretP ps; + + /** + * Blinding keys used to blind the fresh coin. + */ + union TALER_DenominationBlindingKeyP bks; + + /** + * Signature affirming the validity of the coin. + */ + struct TALER_DenominationSignature sig; + +}; + + +/** + * Result of a /refreshes/$RCH/reveal request. + */ +struct TALER_EXCHANGE_RevealResult +{ + /** + * HTTP status. + */ + struct TALER_EXCHANGE_HttpResponse hr; + + /** + * Parsed response details, variant depending on the + * @e hr.http_status. + */ + union + { + /** + * Results for status #MHD_HTTP_SUCCESS. + */ + struct + { + /** + * Array of @e num_coins values about the coins obtained via the refresh + * operation. The array give the coins in the same order (and should + * have the same length) in which the original melt request specified the + * respective denomination keys. + */ + const struct TALER_EXCHANGE_RevealedCoinInfo *coins; + + /** + * Number of coins returned. + */ + unsigned int num_coins; + } success; + + } details; + +}; + + /** * Callbacks of this type are used to return the final result of * submitting a refresh request to a exchange. If the operation was * successful, this function returns the signatures over the coins - * that were remelted. The @a coin_privs and @a sigs arrays give the - * coins in the same order (and should have the same length) in which - * the original request specified the respective denomination keys. + * that were remelted. * * @param cls closure - * @param hr HTTP response data - * @param num_coins number of fresh coins created, length of the @a sigs and @a coin_privs arrays, 0 if the operation failed - * @param coin_privs array of @a num_coins private keys for the coins that were created, NULL on error - * @param sigs array of signature over @a num_coins coins, NULL on error + * @param rr result of the reveal operation */ typedef void (*TALER_EXCHANGE_RefreshesRevealCallback)( void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - unsigned int num_coins, - const struct TALER_PlanchetSecretsP *coin_privs, - const struct TALER_DenominationSignature *sigs); + const struct TALER_EXCHANGE_RevealResult *rr); /** @@ -1605,8 +1850,10 @@ struct TALER_EXCHANGE_RefreshesRevealHandle; * prior to calling this function. * * @param exchange the exchange handle; the exchange must be ready to operate - * @param refresh_data the refresh data as returned from - #TALER_EXCHANGE_refresh_prepare()) + * @param rms the fresh secret that defines the refresh operation + * @param rd the refresh data that characterizes the refresh operation + * @param num_coins number of fresh coins to be created, length of the @a exchange_vals array, must match value in @a rd + * @param alg_values array @a num_coins of exchange values contributed to the refresh operation * @param noreveal_index response from the exchange to the * #TALER_EXCHANGE_melt() invocation * @param reveal_cb the callback to call with the final result of the @@ -1618,7 +1865,10 @@ struct TALER_EXCHANGE_RefreshesRevealHandle; struct TALER_EXCHANGE_RefreshesRevealHandle * TALER_EXCHANGE_refreshes_reveal ( struct TALER_EXCHANGE_Handle *exchange, - const json_t *refresh_data, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, + unsigned int num_coins, + const struct TALER_ExchangeWithdrawValues *alg_values, uint32_t noreveal_index, TALER_EXCHANGE_RefreshesRevealCallback reveal_cb, void *reveal_cb_cls); @@ -1644,6 +1894,71 @@ TALER_EXCHANGE_refreshes_reveal_cancel ( struct TALER_EXCHANGE_LinkHandle; +/** + * Information about a coin obtained via /link. + */ +struct TALER_EXCHANGE_LinkedCoinInfo +{ + /** + * Private key of the coin. + */ + struct TALER_CoinSpendPrivateKeyP coin_priv; + + /** + * Master secret of this coin. + */ + struct TALER_PlanchetMasterSecretP ps; + + /** + * Signature affirming the validity of the coin. + */ + struct TALER_DenominationSignature sig; + + /** + * Denomination public key of the coin. + */ + struct TALER_DenominationPublicKey pub; +}; + + +/** + * Result of a /link request. + */ +struct TALER_EXCHANGE_LinkResult +{ + /** + * HTTP status. + */ + struct TALER_EXCHANGE_HttpResponse hr; + + /** + * Parsed response details, variant depending on the + * @e hr.http_status. + */ + union + { + /** + * Results for status #MHD_HTTP_SUCCESS. + */ + struct + { + /** + * Array of @e num_coins values about the + * coins obtained via linkage. + */ + const struct TALER_EXCHANGE_LinkedCoinInfo *coins; + + /** + * Number of coins returned. + */ + unsigned int num_coins; + } success; + + } details; + +}; + + /** * Callbacks of this type are used to return the final result of submitting a * /coins/$COIN_PUB/link request to a exchange. If the operation was @@ -1651,20 +1966,12 @@ struct TALER_EXCHANGE_LinkHandle; * created when the original coin was melted. * * @param cls closure - * @param hr HTTP response data - * @param num_coins number of fresh coins created, length of the @a sigs and @a coin_privs arrays, 0 if the operation failed - * @param coin_privs array of @a num_coins private keys for the coins that were created, NULL on error - * @param sigs array of signature over @a num_coins coins, NULL on error - * @param pubs array of public keys for the @a sigs, NULL on error + * @param lr result of the /link operation */ typedef void (*TALER_EXCHANGE_LinkCallback) ( void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - unsigned int num_coins, - const struct TALER_CoinSpendPrivateKeyP *coin_privs, - const struct TALER_DenominationSignature *sigs, - const struct TALER_DenominationPublicKey *pubs); + const struct TALER_EXCHANGE_LinkResult *lr); /** @@ -1897,8 +2204,7 @@ struct TALER_EXCHANGE_GetDepositResponse * Function called with detailed wire transfer data. * * @param cls closure - * @param hr HTTP response data - * @param dd details about the deposit (NULL on errors) + * @param dr details about the deposit response */ typedef void (*TALER_EXCHANGE_DepositGetCallback)( @@ -2037,6 +2343,7 @@ typedef void * @param exchange the exchange handle; the exchange must be ready to operate * @param pk kind of coin to pay back * @param denom_sig signature over the coin by the exchange using @a pk + * @param exchange_vals contribution from the exchange on the withdraw * @param ps secret internals of the original planchet * @param recoup_cb the callback to call when the final result for this request is available * @param recoup_cb_cls closure for @a recoup_cb @@ -2048,7 +2355,8 @@ struct TALER_EXCHANGE_RecoupHandle * TALER_EXCHANGE_recoup (struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_DenominationSignature *denom_sig, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *exchange_vals, + const struct TALER_PlanchetMasterSecretP *ps, TALER_EXCHANGE_RecoupResultCallback recoup_cb, void *recoup_cb_cls); @@ -2097,7 +2405,10 @@ typedef void * @param exchange the exchange handle; the exchange must be ready to operate * @param pk kind of coin to pay back * @param denom_sig signature over the coin by the exchange using @a pk - * @param ps secret internals of the original planchet + * @param exchange_vals contribution from the exchange on the withdraw + * @param rms melt secret of the refreshing operation + * @param ps coin-specific secrets derived for this coin during the refreshing operation + * @param idx index of the fresh coin in the refresh operation that is now being recouped * @param recoup_cb the callback to call when the final result for this request is available * @param recoup_cb_cls closure for @a recoup_cb * @return NULL @@ -2109,7 +2420,10 @@ TALER_EXCHANGE_recoup_refresh ( struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_DenominationSignature *denom_sig, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *exchange_vals, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_PlanchetMasterSecretP *ps, + unsigned int idx, TALER_EXCHANGE_RecoupRefreshResultCallback recoup_cb, void *recoup_cb_cls); @@ -2169,7 +2483,7 @@ struct TALER_EXCHANGE_KycStatus /** * Signature of purpose - * #TALER_SIGNATURE_ACCOUNT_SETUP_SUCCESS affirming + * #TALER_SIGNATURE_EXCHANGE_ACCOUNT_SETUP_SUCCESS affirming * the successful KYC process. */ struct TALER_ExchangeSignatureP exchange_sig; @@ -2263,7 +2577,7 @@ struct TALER_EXCHANGE_KycProofResponse * Function called with the result of a KYC check. * * @param cls closure - * @param ks the account's KYC status details + * @param kpr the account's KYC status details */ typedef void (*TALER_EXCHANGE_KycProofCallback)( @@ -2500,10 +2814,15 @@ struct TALER_EXCHANGE_FutureKeys struct TALER_SecurityModulePublicKeyP signkey_secmod_public_key; /** - * Public key of the denomination security module. + * Public key of the RSA denomination security module. */ struct TALER_SecurityModulePublicKeyP denom_secmod_public_key; + /** + * Public key of the CS denomination security module. + */ + struct TALER_SecurityModulePublicKeyP denom_secmod_cs_public_key; + /** * Offline master public key used by this exchange. */ diff --git a/src/include/taler_exchangedb_plugin.h b/src/include/taler_exchangedb_plugin.h index 2bbf65b01..f0a6f8bd6 100644 --- a/src/include/taler_exchangedb_plugin.h +++ b/src/include/taler_exchangedb_plugin.h @@ -323,6 +323,7 @@ struct TALER_EXCHANGEDB_TableData uint64_t denominations_serial; void *coin_ev; size_t coin_ev_size; + struct TALER_ExchangeWithdrawValues ewv; // h_coin_ev omitted, to be recomputed! struct TALER_BlindedDenominationSignature ev_sig; } refresh_revealed_coins; @@ -346,7 +347,7 @@ struct TALER_EXCHANGEDB_TableData struct TALER_MerchantPublicKeyP merchant_pub; struct TALER_PrivateContractHash h_contract_terms; struct TALER_CoinSpendSignatureP coin_sig; - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; uint64_t wire_target_serial_id; bool tiny; bool done; @@ -1033,7 +1034,7 @@ struct TALER_EXCHANGEDB_Deposit /** * Salt used by the merchant to compute "h_wire". */ - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; /** * Information about the receiver for executing the transaction. URI in @@ -1132,7 +1133,7 @@ struct TALER_EXCHANGEDB_DepositListEntry /** * Salt used to compute h_wire from the @e receiver_wire_account. */ - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; /** * Time when this request was generated. Used, for example, to @@ -1388,12 +1389,32 @@ struct TALER_EXCHANGEDB_LinkList */ struct TALER_BlindedDenominationSignature ev_sig; + /** + * Exchange-provided values during the coin generation. + */ + struct TALER_ExchangeWithdrawValues alg_values; + /** * Signature of the original coin being refreshed over the * link data, of type #TALER_SIGNATURE_WALLET_COIN_LINK */ struct TALER_CoinSpendSignatureP orig_coin_link_sig; + /** + * CS nonce, if cipher is CS. + */ + struct TALER_CsNonce nonce; + + /** + * Offset that generated this coin in the refresh + * operation. + */ + uint32_t coin_refresh_offset; + + /** + * Set to true if @e nonce was initialized. + */ + bool have_nonce; }; @@ -1668,14 +1689,15 @@ struct TALER_EXCHANGEDB_RefreshRevealedCoin struct TALER_BlindedDenominationSignature coin_sig; /** - * Blinded message to be signed (in envelope), with @e coin_env_size bytes. + * Values contributed from the exchange to the + * coin generation (see /csr). */ - void *coin_ev; + struct TALER_ExchangeWithdrawValues exchange_vals; /** - * Number of bytes in @e coin_ev. + * Blinded message to be signed (in envelope). */ - size_t coin_ev_size; + struct TALER_BlindedPlanchet blinded_planchet; }; @@ -1895,7 +1917,6 @@ typedef void * @param cls closure * @param rowid which row in the table is the information from (for diagnostics) * @param merchant_pub public key of the merchant (should be same for all callbacks with the same @e cls) - * @param h_wire hash of wire transfer details of the merchant (should be same for all callbacks with the same @e cls) * @param account_payto_uri which account did the transfer go to? * @param exec_time execution time of the wire transfer (should be same for all callbacks with the same @e cls) * @param h_contract_terms which proposal was this payment about @@ -2477,20 +2498,19 @@ struct TALER_EXCHANGEDB_Plugin /** - * Locate the response for a withdraw request under the - * key of the hash of the blinded message. Used to ensure - * idempotency of the request. + * Locate the response for a withdraw request under a hash that uniquely + * identifies the withdraw operation. Used to ensure idempotency of the + * request. * * @param cls the @e cls of this struct with the plugin-specific state - * @param h_blind hash of the blinded coin to be signed (will match - * `h_coin_envelope` in the @a collectable to be returned) - * @param collectable corresponding collectable coin (blind signature) + * @param wih hash that uniquely identifies the withdraw operation + * @param[out] collectable corresponding collectable coin (blind signature) * if a coin is found * @return statement execution status */ enum GNUNET_DB_QueryStatus (*get_withdraw_info)(void *cls, - const struct TALER_BlindedCoinHash *h_blind, + const struct TALER_WithdrawIdentificationHash *wih, struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable); @@ -2499,7 +2519,8 @@ struct TALER_EXCHANGEDB_Plugin * and possibly persisting the withdrawal details. * * @param cls the `struct PostgresClosure` with the plugin-specific state - * @param collectable corresponding collectable coin (blind signature) + * @param wih hash that uniquely identifies the withdraw operation + * @param[in,out] collectable corresponding collectable coin (blind signature) * if a coin is found * @param now current time (rounded) * @param[out] found set to true if the reserve was found @@ -2511,7 +2532,8 @@ struct TALER_EXCHANGEDB_Plugin enum GNUNET_DB_QueryStatus (*do_withdraw)( void *cls, - const struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable, + const struct TALER_WithdrawIdentificationHash *wih, + struct TALER_EXCHANGEDB_CollectableBlindcoin *collectable, struct GNUNET_TIME_Timestamp now, bool *found, bool *balance_ok, @@ -2547,6 +2569,7 @@ struct TALER_EXCHANGEDB_Plugin * @param deposit deposit operation details * @param known_coin_id row of the coin in the known_coins table * @param h_payto hash of the merchant's payto URI + * @param extension_blocked true if an extension is blocking the wire transfer * @param[in,out] exchange_timestamp time to use for the deposit (possibly updated) * @param[out] balance_ok set to true if the balance was sufficient * @param[out] in_conflict set to true if the deposit conflicted @@ -3517,16 +3540,16 @@ struct TALER_EXCHANGEDB_Plugin * from given the hash of the blinded coin. * * @param cls closure - * @param h_blind_ev hash of the blinded coin + * @param wih hash identifying the withdraw operation * @param[out] reserve_pub set to information about the reserve (on success only) * @param[out] reserve_out_serial_id set to row of the @a h_blind_ev in reserves_out * @return transaction status code */ enum GNUNET_DB_QueryStatus - (*get_reserve_by_h_blind)(void *cls, - const struct TALER_BlindedCoinHash *h_blind_ev, - struct TALER_ReservePublicKeyP *reserve_pub, - uint64_t *reserve_out_serial_id); + (*get_reserve_by_wih)(void *cls, + const struct TALER_WithdrawIdentificationHash *wih, + struct TALER_ReservePublicKeyP *reserve_pub, + uint64_t *reserve_out_serial_id); /** diff --git a/src/include/taler_json_lib.h b/src/include/taler_json_lib.h index df95e042b..e3e47222b 100644 --- a/src/include/taler_json_lib.h +++ b/src/include/taler_json_lib.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014, 2015, 2016, 2021 Taler Systems SA + Copyright (C) 2014, 2015, 2016, 2021, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -117,6 +117,34 @@ TALER_JSON_pack_blinded_denom_sig ( const struct TALER_BlindedDenominationSignature *sig); +/** + * Generate packer instruction for a JSON field of type + * blinded planchet. + * + * @param name name of the field to add to the object + * @param blinded_planchet blinded planchet + * @return json pack specification + */ +struct GNUNET_JSON_PackSpec +TALER_JSON_pack_blinded_planchet ( + const char *name, + const struct TALER_BlindedPlanchet *blinded_planchet); + + +/** + * Generate packer instruction for a JSON field of type + * exchange withdraw values (/csr). + * + * @param name name of the field to add to the object + * @param ewv values to transmit + * @return json pack specification + */ +struct GNUNET_JSON_PackSpec +TALER_JSON_pack_exchange_withdraw_values ( + const char *name, + const struct TALER_ExchangeWithdrawValues *ewv); + + /** * Generate packer instruction for a JSON field of type * amount. @@ -238,7 +266,7 @@ TALER_JSON_spec_denom_pub (const char *field, * Generate line in parser specification for denomination signature. * * @param field name of the field - * @param sig the signature to initialize + * @param[out] sig the signature to initialize * @return corresponding field spec */ struct GNUNET_JSON_Specification @@ -251,7 +279,7 @@ TALER_JSON_spec_denom_sig (const char *field, * blinded denomination signature. * * @param field name of the field - * @param sig the blinded signature to initialize + * @param[out] sig the blinded signature to initialize * @return corresponding field spec */ struct GNUNET_JSON_Specification @@ -260,6 +288,33 @@ TALER_JSON_spec_blinded_denom_sig ( struct TALER_BlindedDenominationSignature *sig); +/** + * Generate line in parser specification for + * exchange withdraw values (/csr). + * + * @param field name of the field + * @param[out] ewv the exchange withdraw values to initialize + * @return corresponding field spec + */ +struct GNUNET_JSON_Specification +TALER_JSON_spec_exchange_withdraw_values ( + const char *field, + struct TALER_ExchangeWithdrawValues *ewv); + + +/** + * Generate line in parser specification for a + * blinded planchet. + * + * @param field name of the field + * @param[out] blinded_planchet the blinded planchet to initialize + * @return corresponding field spec + */ +struct GNUNET_JSON_Specification +TALER_JSON_spec_blinded_planchet (const char *field, + struct TALER_BlindedPlanchet *blinded_planchet); + + /** * The expected field stores a possibly internationalized string. * Internationalization means that there is another field "$name_i18n" @@ -552,6 +607,12 @@ enum GNUNET_GenericReturnValue TALER_JSON_extensions_config_hash (const json_t *config, struct TALER_ExtensionConfigHash *eh); +/** + * Canonicalize a JSON input to a string according to RFC 8785. + */ +char * +TALER_JSON_canonicalize (const json_t *input); + #endif /* TALER_JSON_LIB_H_ */ /* End of taler_json_lib.h */ diff --git a/src/include/taler_mhd_lib.h b/src/include/taler_mhd_lib.h index b0012a645..dc68df06b 100644 --- a/src/include/taler_mhd_lib.h +++ b/src/include/taler_mhd_lib.h @@ -547,7 +547,7 @@ struct TALER_MHD_Legal; /** * Load set of legal documents as specified in @a cfg in section @a section - * where the Etag is given under the @param tagoption and the directory under + * where the Etag is given under the @a tagoption and the directory under * the @a diroption. * * @param cfg configuration to use diff --git a/src/include/taler_pq_lib.h b/src/include/taler_pq_lib.h index 2189a4f61..fdc17ca55 100644 --- a/src/include/taler_pq_lib.h +++ b/src/include/taler_pq_lib.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014, 2015, 2016 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -58,7 +58,7 @@ TALER_PQ_query_param_amount (const struct TALER_Amount *x); * public key will be serialized into on variable-size * BLOB. * - * @param x pointer to the query parameter to pass + * @param denom_pub pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam TALER_PQ_query_param_denom_pub ( @@ -70,25 +70,50 @@ TALER_PQ_query_param_denom_pub ( * various attributes of the signature will be serialized into on * variable-size BLOB. * - * @param x pointer to the query parameter to pass + * @param denom_sig pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam TALER_PQ_query_param_denom_sig ( const struct TALER_DenominationSignature *denom_sig); +/** + * Generate query parameter for a blinded planchet. + * Internally, various attributes of the blinded + * planchet will be serialized into on + * variable-size BLOB. + * + * @param bp pointer to the query parameter to pass + */ +struct GNUNET_PQ_QueryParam +TALER_PQ_query_param_blinded_planchet ( + const struct TALER_BlindedPlanchet *bp); + + /** * Generate query parameter for a blinded denomination signature. Internally, * the various attributes of the signature will be serialized into on * variable-size BLOB. * - * @param x pointer to the query parameter to pass + * @param denom_sig pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam TALER_PQ_query_param_blinded_denom_sig ( const struct TALER_BlindedDenominationSignature *denom_sig); +/** + * Generate query parameter for the exchange's contribution during a + * withdraw. Internally, the various attributes of the @a alg_values will be + * serialized into on variable-size BLOB. + * + * @param alg_values pointer to the query parameter to pass + */ +struct GNUNET_PQ_QueryParam +TALER_PQ_query_param_exchange_withdraw_values ( + const struct TALER_ExchangeWithdrawValues *alg_values); + + /** * Generate query parameter for a JSON object (stored as a string * in the DB). Note that @a x must really be a JSON object or array, @@ -166,6 +191,32 @@ TALER_PQ_result_spec_blinded_denom_sig ( struct TALER_BlindedDenominationSignature *denom_sig); +/** + * Exchange withdraw values expected. + * + * @param name name of the field in the table + * @param[out] ewv where to store the exchange values + * @return array entry for the result specification to use + */ +struct GNUNET_PQ_ResultSpec +TALER_PQ_result_spec_exchange_withdraw_values ( + const char *name, + struct TALER_ExchangeWithdrawValues *ewv); + + +/** + * Blinded planchet expected. + * + * @param name name of the field in the table + * @param[out] bp where to store the blinded planchet + * @return array entry for the result specification to use + */ +struct GNUNET_PQ_ResultSpec +TALER_PQ_result_spec_blinded_planchet ( + const char *name, + struct TALER_BlindedPlanchet *bp); + + /** * json_t expected. * diff --git a/src/include/taler_signatures.h b/src/include/taler_signatures.h index 7ea01f211..e3d9a8939 100644 --- a/src/include/taler_signatures.h +++ b/src/include/taler_signatures.h @@ -164,7 +164,6 @@ */ #define TALER_SIGNATURE_EXCHANGE_AFFIRM_DENOM_UNKNOWN 1042 - /** * Signature where the Exchange confirms that it does not consider a denomination valid for the given operation * at this time. @@ -287,6 +286,11 @@ */ #define TALER_SIGNATURE_SM_SIGNING_KEY 1251 +/** + * Signature on a denomination key announcement. + */ +#define TALER_SIGNATURE_SM_CS_DENOMINATION_KEY 1252 + /*******************/ /* Test signatures */ /*******************/ @@ -341,7 +345,7 @@ struct TALER_DenominationKeyAnnouncementPS /** * Hash of the denomination public key. */ - struct TALER_RsaPubHashP h_rsa; + struct TALER_DenominationHash h_denom; /** * Hash of the section name in the configuration of this denomination. @@ -440,13 +444,7 @@ struct TALER_WithdrawRequestPS struct GNUNET_CRYPTO_EccSignaturePurpose purpose; /** - * Reserve public key (which reserve to withdraw from). This is - * the public key which must match the signature. - */ - struct TALER_ReservePublicKeyP reserve_pub; - - /** - * Value of the coin being exchangeed (matching the denomination key) + * Value of the coin being exchanged (matching the denomination key) * plus the transaction fee. We include this in what is being * signed so that we can verify a reserve's remaining total balance * without needing to access the respective denomination key @@ -1234,7 +1232,7 @@ struct TALER_MerchantWireDetailsPS /** * Salted hash over the account holder's payto:// URL and - * the salt, as done by #TALER_exchange_wire_signature_hash(). + * the salt, as done by #TALER_merchant_wire_signature_hash(). */ struct TALER_MerchantWireHash h_wire_details GNUNET_PACKED; diff --git a/src/include/taler_testing_lib.h b/src/include/taler_testing_lib.h index f40232e2f..ab8b64fc5 100644 --- a/src/include/taler_testing_lib.h +++ b/src/include/taler_testing_lib.h @@ -1,6 +1,6 @@ /* This file is part of TALER - (C) 2018 Taler Systems SA + (C) 2018-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as @@ -1000,10 +1000,11 @@ TALER_TESTING_cmd_bank_debits (const char *label, /** * Create transfer command. * - * @param label command label. - * @param amount amount to transfer. + * @param label command label + * @param amount amount to transfer * @param auth authentication data to use - * @param payto_credit_account which account receives money. + * @param payto_debit_account which account to withdraw money from + * @param payto_credit_account which account receives money * @param wtid wire transfer identifier to use * @param exchange_base_url exchange URL to use * @return the command. @@ -1715,14 +1716,13 @@ TALER_TESTING_cmd_check_bank_empty (const char *label); * provide a coin to be refunded. * @param refund_transaction_id transaction id to use * in the request. - * * @return the command. */ struct TALER_TESTING_Command TALER_TESTING_cmd_refund_with_id (const char *label, unsigned int expected_response_code, const char *refund_amount, - const char *deposit_reference, + const char *coin_reference, uint64_t refund_transaction_id); @@ -1734,14 +1734,13 @@ TALER_TESTING_cmd_refund_with_id (const char *label, * @param refund_amount the amount to ask a refund for. * @param coin_reference reference to a command that can * provide a coin to be refunded. - * * @return the command. */ struct TALER_TESTING_Command TALER_TESTING_cmd_refund (const char *label, unsigned int expected_response_code, const char *refund_amount, - const char *deposit_reference); + const char *coin_reference); /** @@ -2090,6 +2089,7 @@ TALER_TESTING_cmd_auditor_add_denom_sig (const char *label, const char *denom_ref, bool bad_sig); + /** * Add statement about wire fees of the exchange. This is always * done for a few hours around the current time (for the test). @@ -2227,26 +2227,6 @@ TALER_TESTING_cmd_revoke_sign_key ( const char *signkey_ref); -/** - * Have the auditor affirm that it is auditing the given - * denomination key and upload the auditor's signature to - * the exchange. - * - * @param label command label. - * @param expected_http_status expected HTTP status from exchange - * @param denom_ref reference to a command that identifies - * a denomination key (i.e. because it was used to - * withdraw a coin). - * @param bad_sig should we use a bogus signature? - * @return the command - */ -struct TALER_TESTING_Command -TALER_TESTING_cmd_auditor_add_denom_sig (const char *label, - unsigned int expected_http_status, - const char *denom_ref, - bool bad_sig); - - /** * Create a request for a wallet's KYC UUID. * @@ -2462,6 +2442,8 @@ TALER_TESTING_get_trait (const struct TALER_TESTING_Trait *traits, #define TALER_TESTING_SIMPLE_TRAITS(op) \ op (bank_row, const uint64_t) \ op (reserve_priv, const struct TALER_ReservePrivateKeyP) \ + op (planchet_secret, const struct TALER_PlanchetMasterSecretP) \ + op (refresh_secret, const struct TALER_RefreshMasterSecretP) \ op (reserve_pub, const struct TALER_ReservePublicKeyP) \ op (merchant_priv, const struct TALER_MerchantPrivateKeyP) \ op (merchant_pub, const struct TALER_MerchantPublicKeyP) \ @@ -2503,6 +2485,8 @@ TALER_TESTING_get_trait (const struct TALER_TESTING_Trait *traits, op (denom_sig, const struct TALER_DenominationSignature) \ op (age_commitment, struct TALER_AgeCommitment) \ op (h_age_commitment, struct TALER_AgeCommitmentHash) \ + op (planchet_secrets, const struct TALER_PlanchetMasterSecretP) \ + op (exchange_wd_value, const struct TALER_ExchangeWithdrawValues) \ op (coin_priv, const struct TALER_CoinSpendPrivateKeyP) \ op (coin_pub, const struct TALER_CoinSpendPublicKeyP) \ op (absolute_time, const struct GNUNET_TIME_Absolute) \ diff --git a/src/include/taler_util.h b/src/include/taler_util.h index 26440cb1d..b7b748698 100644 --- a/src/include/taler_util.h +++ b/src/include/taler_util.h @@ -131,6 +131,7 @@ TALER_b2s (const void *buf, /** * Obtain denomination amount from configuration file. * + * @param cfg configuration to extract data from * @param section section of the configuration to access * @param option option of the configuration to access * @param[out] denom set to the amount found in configuration @@ -329,7 +330,7 @@ TALER_payto_get_method (const char *payto_uri); /** * Construct a payto://-URI from a Taler @a reserve_pub at - * a @exchange_base_url + * @a exchange_base_url * * @param exchange_base_url the URL of the exchange * @param reserve_pub public key of the reserve @@ -444,7 +445,7 @@ TALER_yna_to_string (enum TALER_EXCHANGE_YesNoAll yna); * @param c the character to search for * @return char* the first occurence of `c` in `s` */ -char * strchrnul (const char *s, int c); +char *strchrnul (const char *s, int c); #endif diff --git a/src/json/json.c b/src/json/json.c index 705cfe92b..da4472522 100644 --- a/src/json/json.c +++ b/src/json/json.c @@ -78,27 +78,27 @@ lowdump (struct GNUNET_Buffer *buf, { case 0x8: GNUNET_buffer_write (buf, - "\b", + "\\b", 2); break; case 0x9: GNUNET_buffer_write (buf, - "\t", + "\\t", 2); break; case 0xA: GNUNET_buffer_write (buf, - "\n", + "\\n", 2); break; case 0xC: GNUNET_buffer_write (buf, - "\f", + "\\f", 2); break; case 0xD: GNUNET_buffer_write (buf, - "\r", + "\\r", 2); break; default: @@ -144,6 +144,9 @@ rfc8785encode (char **inp) if ( (1 == mbl) && (val <= 0x1F) ) { + /* Should not happen, as input is produced by + * JSON stringification */ + GNUNET_break (0); lowdump (&buf, val); } @@ -193,6 +196,12 @@ rfc8785encode (char **inp) } } break; + default: + mbl = 2; + GNUNET_buffer_write (&buf, + pos, + mbl); + break; } } else @@ -1009,6 +1018,24 @@ TALER_deposit_extension_hash (const json_t *extensions, } +char * +TALER_JSON_canonicalize (const json_t *input) +{ + char *wire_enc; + + if (NULL == (wire_enc = json_dumps (input, + JSON_ENCODE_ANY + | JSON_COMPACT + | JSON_SORT_KEYS))) + { + GNUNET_break (0); + return NULL; + } + rfc8785encode (&wire_enc); + return wire_enc; +} + + enum GNUNET_GenericReturnValue TALER_JSON_extensions_config_hash (const json_t *config, struct TALER_ExtensionConfigHash *ech) diff --git a/src/json/json_helper.c b/src/json/json_helper.c index 949354e24..4ec9a6982 100644 --- a/src/json/json_helper.c +++ b/src/json/json_helper.c @@ -26,6 +26,25 @@ #include "taler_json_lib.h" +/** + * Convert string value to numeric cipher value. + * + * @param cipher_s input string + * @return numeric cipher value + */ +static enum TALER_DenominationCipher +string_to_cipher (const char *cipher_s) +{ + if (0 == strcasecmp (cipher_s, + "RSA")) + return TALER_DENOMINATION_RSA; + if (0 == strcasecmp (cipher_s, + "CS")) + return TALER_DENOMINATION_CS; + return TALER_DENOMINATION_INVALID; +} + + json_t * TALER_JSON_from_amount (const struct TALER_Amount *amount) { @@ -229,9 +248,9 @@ parse_denom_pub (void *cls, struct GNUNET_JSON_Specification *spec) { struct TALER_DenominationPublicKey *denom_pub = spec->ptr; - uint32_t cipher; + const char *cipher; struct GNUNET_JSON_Specification dspec[] = { - GNUNET_JSON_spec_uint32 ("cipher", + GNUNET_JSON_spec_string ("cipher", &cipher), GNUNET_JSON_spec_uint32 ("age_mask", &denom_pub->age_mask.mask), @@ -250,7 +269,7 @@ parse_denom_pub (void *cls, GNUNET_break_op (0); return GNUNET_SYSERR; } - denom_pub->cipher = (enum TALER_DenominationCipher) cipher; + denom_pub->cipher = string_to_cipher (cipher); switch (denom_pub->cipher) { case TALER_DENOMINATION_RSA: @@ -262,6 +281,26 @@ parse_denom_pub (void *cls, GNUNET_JSON_spec_end () }; + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + case TALER_DENOMINATION_CS: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_fixed ("cs_public_key", + &denom_pub->details.cs_public_key, + sizeof (denom_pub->details.cs_public_key)), + GNUNET_JSON_spec_end () + }; + if (GNUNET_OK != GNUNET_JSON_parse (root, ispec, @@ -326,9 +365,9 @@ parse_denom_sig (void *cls, struct GNUNET_JSON_Specification *spec) { struct TALER_DenominationSignature *denom_sig = spec->ptr; - uint32_t cipher; + const char *cipher; struct GNUNET_JSON_Specification dspec[] = { - GNUNET_JSON_spec_uint32 ("cipher", + GNUNET_JSON_spec_string ("cipher", &cipher), GNUNET_JSON_spec_end () }; @@ -345,7 +384,7 @@ parse_denom_sig (void *cls, GNUNET_break_op (0); return GNUNET_SYSERR; } - denom_sig->cipher = (enum TALER_DenominationCipher) cipher; + denom_sig->cipher = string_to_cipher (cipher); switch (denom_sig->cipher) { case TALER_DENOMINATION_RSA: @@ -357,6 +396,27 @@ parse_denom_sig (void *cls, GNUNET_JSON_spec_end () }; + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + case TALER_DENOMINATION_CS: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_fixed_auto ("cs_signature_r", + &denom_sig->details.cs_signature.r_point), + GNUNET_JSON_spec_fixed_auto ("cs_signature_s", + &denom_sig->details.cs_signature.s_scalar), + GNUNET_JSON_spec_end () + }; + if (GNUNET_OK != GNUNET_JSON_parse (root, ispec, @@ -421,9 +481,9 @@ parse_blinded_denom_sig (void *cls, struct GNUNET_JSON_Specification *spec) { struct TALER_BlindedDenominationSignature *denom_sig = spec->ptr; - uint32_t cipher; + const char *cipher; struct GNUNET_JSON_Specification dspec[] = { - GNUNET_JSON_spec_uint32 ("cipher", + GNUNET_JSON_spec_string ("cipher", &cipher), GNUNET_JSON_spec_end () }; @@ -440,7 +500,7 @@ parse_blinded_denom_sig (void *cls, GNUNET_break_op (0); return GNUNET_SYSERR; } - denom_sig->cipher = (enum TALER_DenominationCipher) cipher; + denom_sig->cipher = string_to_cipher (cipher); switch (denom_sig->cipher) { case TALER_DENOMINATION_RSA: @@ -463,6 +523,29 @@ parse_blinded_denom_sig (void *cls, } return GNUNET_OK; } + case TALER_DENOMINATION_CS: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_uint32 ("b", + &denom_sig->details.blinded_cs_answer.b), + GNUNET_JSON_spec_fixed_auto ("s", + &denom_sig->details.blinded_cs_answer. + s_scalar), + GNUNET_JSON_spec_end () + }; + + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + break; default: GNUNET_break_op (0); return GNUNET_SYSERR; @@ -503,6 +586,214 @@ TALER_JSON_spec_blinded_denom_sig ( } +/** + * Parse given JSON object to blinded planchet. + * + * @param cls closure, NULL + * @param root the json object representing data + * @param[out] spec where to write the data + * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error + */ +static enum GNUNET_GenericReturnValue +parse_blinded_planchet (void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) +{ + struct TALER_BlindedPlanchet *blinded_planchet = spec->ptr; + const char *cipher; + struct GNUNET_JSON_Specification dspec[] = { + GNUNET_JSON_spec_string ("cipher", + &cipher), + GNUNET_JSON_spec_end () + }; + const char *emsg; + unsigned int eline; + + (void) cls; + if (GNUNET_OK != + GNUNET_JSON_parse (root, + dspec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + blinded_planchet->cipher = string_to_cipher (cipher); + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_varsize ( + "rsa_blinded_planchet", + &blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + &blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size), + GNUNET_JSON_spec_end () + }; + + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + case TALER_DENOMINATION_CS: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_fixed_auto ( + "cs_nonce", + &blinded_planchet->details.cs_blinded_planchet.nonce), + GNUNET_JSON_spec_fixed_auto ( + "cs_blinded_c0", + &blinded_planchet->details.cs_blinded_planchet.c[0]), + GNUNET_JSON_spec_fixed_auto ( + "cs_blinded_c1", + &blinded_planchet->details.cs_blinded_planchet.c[1]), + GNUNET_JSON_spec_end () + }; + + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + break; + default: + GNUNET_break_op (0); + return GNUNET_SYSERR; + } +} + + +/** + * Cleanup data left from parsing blinded planchet. + * + * @param cls closure, NULL + * @param[out] spec where to free the data + */ +static void +clean_blinded_planchet (void *cls, + struct GNUNET_JSON_Specification *spec) +{ + struct TALER_BlindedPlanchet *blinded_planchet = spec->ptr; + + (void) cls; + TALER_blinded_planchet_free (blinded_planchet); +} + + +struct GNUNET_JSON_Specification +TALER_JSON_spec_blinded_planchet (const char *field, + struct TALER_BlindedPlanchet *blinded_planchet) +{ + struct GNUNET_JSON_Specification ret = { + .parser = &parse_blinded_planchet, + .cleaner = &clean_blinded_planchet, + .field = field, + .ptr = blinded_planchet + }; + + return ret; +} + + +/** + * Parse given JSON object to exchange withdraw values (/csr). + * + * @param cls closure, NULL + * @param root the json object representing data + * @param[out] spec where to write the data + * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error + */ +static enum GNUNET_GenericReturnValue +parse_exchange_withdraw_values (void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) +{ + struct TALER_ExchangeWithdrawValues *ewv = spec->ptr; + const char *cipher; + struct GNUNET_JSON_Specification dspec[] = { + GNUNET_JSON_spec_string ("cipher", + &cipher), + GNUNET_JSON_spec_end () + }; + const char *emsg; + unsigned int eline; + + (void) cls; + if (GNUNET_OK != + GNUNET_JSON_parse (root, + dspec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + ewv->cipher = string_to_cipher (cipher); + switch (ewv->cipher) + { + case TALER_DENOMINATION_RSA: + return GNUNET_OK; + case TALER_DENOMINATION_CS: + { + struct GNUNET_JSON_Specification ispec[] = { + GNUNET_JSON_spec_fixed ( + "r_pub_0", + &ewv->details.cs_values.r_pub[0], + sizeof (struct GNUNET_CRYPTO_CsRPublic)), + GNUNET_JSON_spec_fixed ( + "r_pub_1", + &ewv->details.cs_values.r_pub[1], + sizeof (struct GNUNET_CRYPTO_CsRPublic)), + GNUNET_JSON_spec_end () + }; + + if (GNUNET_OK != + GNUNET_JSON_parse (root, + ispec, + &emsg, + &eline)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + default: + GNUNET_break_op (0); + return GNUNET_SYSERR; + } +} + + +struct GNUNET_JSON_Specification +TALER_JSON_spec_exchange_withdraw_values (const char *field, + struct TALER_ExchangeWithdrawValues * + ewv) +{ + struct GNUNET_JSON_Specification ret = { + .parser = &parse_exchange_withdraw_values, + .field = field, + .ptr = ewv + }; + + return ret; +} + + /** * Closure for #parse_i18n_string. */ diff --git a/src/json/json_pack.c b/src/json/json_pack.c index 6fea72a39..8f888eaf0 100644 --- a/src/json/json_pack.c +++ b/src/json/json_pack.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2021 Taler Systems SA + Copyright (C) 2021, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -61,13 +61,24 @@ TALER_JSON_pack_denom_pub ( case TALER_DENOMINATION_RSA: ps.object = GNUNET_JSON_PACK ( - GNUNET_JSON_pack_uint64 ("cipher", - TALER_DENOMINATION_RSA), + GNUNET_JSON_pack_string ("cipher", + "RSA"), GNUNET_JSON_pack_uint64 ("age_mask", pk->age_mask.mask), GNUNET_JSON_pack_rsa_public_key ("rsa_public_key", pk->details.rsa_public_key)); break; + case TALER_DENOMINATION_CS: + ps.object + = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "CS"), + GNUNET_JSON_pack_uint64 ("age_mask", + pk->age_mask.mask), + GNUNET_JSON_pack_data_varsize ("cs_public_key", + &pk->details.cs_public_key, + sizeof (pk->details.cs_public_key))); + break; default: GNUNET_assert (0); } @@ -87,12 +98,57 @@ TALER_JSON_pack_denom_sig ( switch (sig->cipher) { case TALER_DENOMINATION_RSA: - ps.object - = GNUNET_JSON_PACK ( - GNUNET_JSON_pack_uint64 ("cipher", - TALER_DENOMINATION_RSA), - GNUNET_JSON_pack_rsa_signature ("rsa_signature", - sig->details.rsa_signature)); + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "RSA"), + GNUNET_JSON_pack_rsa_signature ("rsa_signature", + sig->details.rsa_signature)); + break; + case TALER_DENOMINATION_CS: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "CS"), + GNUNET_JSON_pack_data_auto ("cs_signature_r", + &sig->details.cs_signature.r_point), + GNUNET_JSON_pack_data_auto ("cs_signature_s", + &sig->details.cs_signature.s_scalar)); + break; + default: + GNUNET_assert (0); + } + return ps; +} + + +struct GNUNET_JSON_PackSpec +TALER_JSON_pack_exchange_withdraw_values ( + const char *name, + const struct TALER_ExchangeWithdrawValues *ewv) +{ + struct GNUNET_JSON_PackSpec ps = { + .field_name = name, + }; + + switch (ewv->cipher) + { + case TALER_DENOMINATION_RSA: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "RSA")); + break; + case TALER_DENOMINATION_CS: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "CS"), + GNUNET_JSON_pack_data_varsize ( + "r_pub_0", + &ewv->details.cs_values.r_pub[0], + sizeof(struct GNUNET_CRYPTO_CsRPublic)), + GNUNET_JSON_pack_data_varsize ( + "r_pub_1", + &ewv->details.cs_values.r_pub[1], + sizeof(struct GNUNET_CRYPTO_CsRPublic)) + ); break; default: GNUNET_assert (0); @@ -113,12 +169,61 @@ TALER_JSON_pack_blinded_denom_sig ( switch (sig->cipher) { case TALER_DENOMINATION_RSA: - ps.object - = GNUNET_JSON_PACK ( - GNUNET_JSON_pack_uint64 ("cipher", - TALER_DENOMINATION_RSA), - GNUNET_JSON_pack_rsa_signature ("blinded_rsa_signature", - sig->details.blinded_rsa_signature)); + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "RSA"), + GNUNET_JSON_pack_rsa_signature ("blinded_rsa_signature", + sig->details.blinded_rsa_signature)); + break; + case TALER_DENOMINATION_CS: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "CS"), + GNUNET_JSON_pack_uint64 ("b", + sig->details.blinded_cs_answer.b), + GNUNET_JSON_pack_data_auto ("s", + &sig->details.blinded_cs_answer.s_scalar)); + break; + default: + GNUNET_assert (0); + } + return ps; +} + + +struct GNUNET_JSON_PackSpec +TALER_JSON_pack_blinded_planchet ( + const char *name, + const struct TALER_BlindedPlanchet *blinded_planchet) +{ + struct GNUNET_JSON_PackSpec ps = { + .field_name = name, + }; + + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "RSA"), + GNUNET_JSON_pack_data_varsize ( + "rsa_blinded_planchet", + blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size)); + break; + case TALER_DENOMINATION_CS: + ps.object = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_string ("cipher", + "CS"), + GNUNET_JSON_pack_data_auto ( + "cs_nonce", + &blinded_planchet->details.cs_blinded_planchet.nonce), + GNUNET_JSON_pack_data_auto ( + "cs_blinded_c0", + &blinded_planchet->details.cs_blinded_planchet.c[0]), + GNUNET_JSON_pack_data_auto ( + "cs_blinded_c1", + &blinded_planchet->details.cs_blinded_planchet.c[1])); break; default: GNUNET_assert (0); diff --git a/src/json/json_wire.c b/src/json/json_wire.c index 8f7fd6bb6..139f41db1 100644 --- a/src/json/json_wire.c +++ b/src/json/json_wire.c @@ -29,7 +29,7 @@ TALER_JSON_merchant_wire_signature_hash (const json_t *wire_s, struct TALER_MerchantWireHash *hc) { const char *payto_uri; - struct TALER_WireSalt salt; + struct TALER_WireSaltP salt; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_string ("payto_uri", &payto_uri), diff --git a/src/json/test_json.c b/src/json/test_json.c index a8c1c6d8e..5fe51d467 100644 --- a/src/json/test_json.c +++ b/src/json/test_json.c @@ -160,7 +160,7 @@ test_contract (void) GNUNET_assert (GNUNET_OK == TALER_JSON_contract_part_forget (c1, "k2")); - json_dumpf (c1, stderr, JSON_INDENT (2)); + // json_dumpf (c1, stderr, JSON_INDENT (2)); GNUNET_assert (GNUNET_OK == TALER_JSON_contract_hash (c1, &h2)); @@ -182,7 +182,7 @@ test_contract (void) GNUNET_assert (GNUNET_OK == TALER_JSON_contract_hash (c1, &h1)); - json_dumpf (c1, stderr, JSON_INDENT (2)); + // json_dumpf (c1, stderr, JSON_INDENT (2)); json_decref (c1); { char *s; @@ -330,6 +330,57 @@ test_contract (void) } +static int +test_json_canon (void) +{ + { + json_t *c1; + char *canon; + c1 = json_pack ("{s:s}", + "k1", "Hello\nWorld"); + + canon = TALER_JSON_canonicalize (c1); + GNUNET_assert (NULL != canon); + + printf ("canon: '%s'\n", canon); + + GNUNET_assert (0 == strcmp (canon, + "{\"k1\":\"Hello\\nWorld\"}")); + } + { + json_t *c1; + char *canon; + c1 = json_pack ("{s:s}", + "k1", "Testing “unicode” characters"); + + canon = TALER_JSON_canonicalize (c1); + GNUNET_assert (NULL != canon); + + printf ("canon: '%s'\n", canon); + + GNUNET_assert (0 == strcmp (canon, + "{\"k1\":\"Testing “unicode” characters\"}")); + } + { + json_t *c1; + char *canon; + c1 = json_pack ("{s:s}", + "k1", "low range \x05 chars"); + + canon = TALER_JSON_canonicalize (c1); + GNUNET_assert (NULL != canon); + + printf ("canon: '%s'\n", canon); + + GNUNET_assert (0 == strcmp (canon, + "{\"k1\":\"low range \\u0005 chars\"}")); + } + + + return 0; +} + + static int test_rfc8785 (void) { @@ -348,7 +399,7 @@ test_rfc8785 (void) sizeof (h1)); if (0 != strcmp (s, - "J678K3PW9Y3DG63Z3T7ZYR2P7CEXMVZ2SFPQMABACK9TJRYREPP82542PCJ0P7Y7FAQAMWECDX50XH1RBTWHX6SSJHH6FXRV0JCS6R8")) + "531S33T8ZRGW6548G7T67PMDNGS4Z1D8A2GMB87G3PNKYTW6KGF7Q99XVCGXBKVA2HX6PR5ENJ1PQ5ZTYMMXQB6RM7S82VP7ZG2X5G8")) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid reference hash: %s\n", @@ -377,6 +428,8 @@ main (int argc, return 1; if (0 != test_contract ()) return 2; + if (0 != test_json_canon ()) + return 2; if (0 != test_rfc8785 ()) return 2; return 0; diff --git a/src/lib/Makefile.am b/src/lib/Makefile.am index 3398bdf14..fe2a0b6b1 100644 --- a/src/lib/Makefile.am +++ b/src/lib/Makefile.am @@ -24,6 +24,7 @@ libtalerexchange_la_SOURCES = \ exchange_api_auditor_add_denomination.c \ exchange_api_curl_defaults.c exchange_api_curl_defaults.h \ exchange_api_common.c \ + exchange_api_csr.c \ exchange_api_handle.c exchange_api_handle.h \ exchange_api_deposit.c \ exchange_api_deposits_get.c \ diff --git a/src/lib/auditor_api_handle.c b/src/lib/auditor_api_handle.c index 1d5522141..f7d7f9a77 100644 --- a/src/lib/auditor_api_handle.c +++ b/src/lib/auditor_api_handle.c @@ -365,12 +365,6 @@ version_completed_cb (void *cls, /* ********************* library internal API ********* */ -/** - * Get the context of a auditor. - * - * @param h the auditor handle to query - * @return ctx context to execute jobs in - */ struct GNUNET_CURL_Context * TALER_AUDITOR_handle_to_context_ (struct TALER_AUDITOR_Handle *h) { @@ -378,13 +372,7 @@ TALER_AUDITOR_handle_to_context_ (struct TALER_AUDITOR_Handle *h) } -/** - * Check if the handle is ready to process requests. - * - * @param h the auditor handle to query - * @return #GNUNET_YES if we are ready, #GNUNET_NO if not - */ -int +enum GNUNET_GenericReturnValue TALER_AUDITOR_handle_is_ready_ (struct TALER_AUDITOR_Handle *h) { GNUNET_log (GNUNET_ERROR_TYPE_INFO, @@ -396,13 +384,6 @@ TALER_AUDITOR_handle_is_ready_ (struct TALER_AUDITOR_Handle *h) } -/** - * Obtain the URL to use for an API request. - * - * @param h handle for the auditor - * @param path Taler API path (i.e. "/deposit-confirmation") - * @return the full URL to use with cURL - */ char * TALER_AUDITOR_path_to_url_ (struct TALER_AUDITOR_Handle *h, const char *path) @@ -417,21 +398,6 @@ TALER_AUDITOR_path_to_url_ (struct TALER_AUDITOR_Handle *h, /* ********************* public API ******************* */ -/** - * Initialise a connection to the auditor. Will connect to the - * auditor and obtain information about the auditor's master public - * key and the auditor's auditor. The respective information will - * be passed to the @a version_cb once available, and all future - * interactions with the auditor will be checked to be signed - * (where appropriate) by the respective master key. - * - * @param ctx the context - * @param url HTTP base URL for the auditor - * @param version_cb function to call with the - * auditor's version information - * @param version_cb_cls closure for @a version_cb - * @return the auditor handle; NULL upon error - */ struct TALER_AUDITOR_Handle * TALER_AUDITOR_connect (struct GNUNET_CURL_Context *ctx, const char *url, @@ -515,11 +481,6 @@ request_version (void *cls) } -/** - * Disconnect from the auditor - * - * @param auditor the auditor handle - */ void TALER_AUDITOR_disconnect (struct TALER_AUDITOR_Handle *auditor) { diff --git a/src/lib/exchange_api_common.c b/src/lib/exchange_api_common.c index 37d359573..d03409244 100644 --- a/src/lib/exchange_api_common.c +++ b/src/lib/exchange_api_common.c @@ -124,7 +124,8 @@ TALER_EXCHANGE_parse_reserve_history ( "WITHDRAW")) { struct TALER_ReserveSignatureP sig; - struct TALER_WithdrawRequestPS withdraw_purpose; + struct TALER_DenominationHash h_denom_pub; + struct TALER_BlindedCoinHash bch; struct TALER_Amount withdraw_fee; struct GNUNET_JSON_Specification withdraw_spec[] = { GNUNET_JSON_spec_fixed_auto ("reserve_sig", @@ -132,9 +133,9 @@ TALER_EXCHANGE_parse_reserve_history ( TALER_JSON_spec_amount_any ("withdraw_fee", &withdraw_fee), GNUNET_JSON_spec_fixed_auto ("h_denom_pub", - &withdraw_purpose.h_denomination_pub), + &h_denom_pub), GNUNET_JSON_spec_fixed_auto ("h_coin_envelope", - &withdraw_purpose.h_coin_envelope), + &bch), GNUNET_JSON_spec_end () }; @@ -147,19 +148,14 @@ TALER_EXCHANGE_parse_reserve_history ( GNUNET_break_op (0); return GNUNET_SYSERR; } - withdraw_purpose.purpose.size - = htonl (sizeof (withdraw_purpose)); - withdraw_purpose.purpose.purpose - = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW); - withdraw_purpose.reserve_pub = *reserve_pub; - TALER_amount_hton (&withdraw_purpose.amount_with_fee, - &amount); + /* Check that the signature is a valid withdraw request */ if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW, - &withdraw_purpose, - &sig.eddsa_signature, - &reserve_pub->eddsa_pub)) + TALER_wallet_withdraw_verify (&h_denom_pub, + &amount, + &bch, + reserve_pub, + &sig)) { GNUNET_break_op (0); GNUNET_JSON_parse_free (withdraw_spec); @@ -172,8 +168,7 @@ TALER_EXCHANGE_parse_reserve_history ( key_state = TALER_EXCHANGE_get_keys (exchange); dki = TALER_EXCHANGE_get_denomination_key_by_hash (key_state, - &withdraw_purpose. - h_denomination_pub); + &h_denom_pub); if ( (GNUNET_YES != TALER_amount_cmp_currency (&withdraw_fee, &dki->fee_withdraw)) || @@ -193,10 +188,10 @@ TALER_EXCHANGE_parse_reserve_history ( /* Check check that the same withdraw transaction isn't listed twice by the exchange. We use the "uuid" array to remember the hashes of all - purposes, and compare the hashes to find - duplicates. */// - GNUNET_CRYPTO_hash (&withdraw_purpose, - ntohl (withdraw_purpose.purpose.size), + signatures, and compare the hashes to find + duplicates. */ + GNUNET_CRYPTO_hash (&sig, + sizeof (sig), &uuid[uuid_off]); for (unsigned int i = 0; i +*/ +/** + * @file lib/exchange_api_csr.c + * @brief Implementation of /csr requests (get R in exchange used for Clause Schnorr withdraw and refresh) + * @author Lucien Heuzeveldt + * @author Gian Demarmels + */ +#include "platform.h" +#include +#include /* just for HTTP status codes */ +#include +#include +#include +#include "taler_exchange_service.h" +#include "taler_json_lib.h" +#include "exchange_api_handle.h" +#include "taler_signatures.h" +#include "exchange_api_curl_defaults.h" + + +/** + * @brief A Clause Schnorr R Handle + */ +struct TALER_EXCHANGE_CsRHandle +{ + /** + * The connection to exchange this request handle will use + */ + struct TALER_EXCHANGE_Handle *exchange; + + /** + * Function to call with the result. + */ + TALER_EXCHANGE_CsRCallback cb; + + /** + * Closure for @a cb. + */ + void *cb_cls; + + /** + * The url for this request. + */ + char *url; + + /** + * Handle for the request. + */ + struct GNUNET_CURL_Job *job; + + /** + * Context for #TEH_curl_easy_post(). Keeps the data that must + * persist for Curl to make the upload. + */ + struct TALER_CURL_PostContext post_ctx; +}; + + +/** + * We got a 200 OK response for the /reserves/$RESERVE_PUB/withdraw operation. + * Extract the coin's signature and return it to the caller. The signature we + * get from the exchange is for the blinded value. Thus, we first must + * unblind it and then should verify its validity against our coin's hash. + * + * If everything checks out, we return the unblinded signature + * to the application via the callback. + * + * @param csrh operation handle + * @param arr reply from the exchange + * @param hr http response details + * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors + */ +static enum GNUNET_GenericReturnValue +csr_ok (struct TALER_EXCHANGE_CsRHandle *csrh, + json_t *arr, + struct TALER_EXCHANGE_HttpResponse *hr) +{ + unsigned int alen = json_array_size (arr); + struct TALER_ExchangeWithdrawValues alg_values[GNUNET_NZL (alen)]; + struct TALER_EXCHANGE_CsRResponse csrr = { + .hr = *hr, + .details.success.alg_values_len = alen, + .details.success.alg_values = alg_values + }; + + for (unsigned int i = 0; icb (csrh->cb_cls, + &csrr); + return GNUNET_OK; +} + + +/** + * Function called when we're done processing the HTTP /csr request. + * + * @param cls the `struct TALER_EXCHANGE_CsRHandle` + * @param response_code HTTP response code, 0 on error + * @param response parsed JSON result, NULL on error + */ +static void +handle_csr_finished (void *cls, + long response_code, + const void *response) +{ + struct TALER_EXCHANGE_CsRHandle *csrh = cls; + const json_t *j = response; + struct TALER_EXCHANGE_HttpResponse hr = { + .reply = j, + .http_status = (unsigned int) response_code + }; + struct TALER_EXCHANGE_CsRResponse csrr = { + .hr = hr + }; + + csrh->job = NULL; + switch (response_code) + { + case 0: + csrr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; + break; + case MHD_HTTP_OK: + { + json_t *arr; + + arr = json_object_get (j, + "ewvs"); + if ( (NULL == arr) || + (0 == json_array_size (arr)) || + (GNUNET_OK != + csr_ok (csrh, + arr, + &hr)) ) + { + GNUNET_break_op (0); + csrr.hr.http_status = 0; + csrr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; + break; + } + } + TALER_EXCHANGE_csr_cancel (csrh); + return; + case MHD_HTTP_BAD_REQUEST: + /* This should never happen, either us or the exchange is buggy + (or API version conflict); just pass JSON reply to the application */ + csrr.hr.ec = TALER_JSON_get_error_code (j); + csrr.hr.hint = TALER_JSON_get_error_hint (j); + break; + case MHD_HTTP_NOT_FOUND: + /* Nothing really to verify, the exchange basically just says + that it doesn't know the /csr endpoint or denomination. + Can happen if the exchange doesn't support Clause Schnorr. + We should simply pass the JSON reply to the application. */ + csrr.hr.ec = TALER_JSON_get_error_code (j); + csrr.hr.hint = TALER_JSON_get_error_hint (j); + break; + case MHD_HTTP_GONE: + /* could happen if denomination was revoked */ + /* Note: one might want to check /keys for revocation + signature here, alas tricky in case our /keys + is outdated => left to clients */ + csrr.hr.ec = TALER_JSON_get_error_code (j); + csrr.hr.hint = TALER_JSON_get_error_hint (j); + break; + case MHD_HTTP_INTERNAL_SERVER_ERROR: + /* Server had an internal issue; we should retry, but this API + leaves this to the application */ + csrr.hr.ec = TALER_JSON_get_error_code (j); + csrr.hr.hint = TALER_JSON_get_error_hint (j); + break; + default: + /* unexpected response code */ + GNUNET_break_op (0); + csrr.hr.ec = TALER_JSON_get_error_code (j); + csrr.hr.hint = TALER_JSON_get_error_hint (j); + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Unexpected response code %u/%d for CS R request\n", + (unsigned int) response_code, + (int) hr.ec); + break; + } + csrh->cb (csrh->cb_cls, + &csrr); + csrh->cb = NULL; + TALER_EXCHANGE_csr_cancel (csrh); +} + + +struct TALER_EXCHANGE_CsRHandle * +TALER_EXCHANGE_csr (struct TALER_EXCHANGE_Handle *exchange, + unsigned int nks_len, + struct TALER_EXCHANGE_NonceKey *nks, + TALER_EXCHANGE_CsRCallback res_cb, + void *res_cb_cls) +{ + struct TALER_EXCHANGE_CsRHandle *csrh; + json_t *csr_arr; + + if (0 == nks_len) + { + GNUNET_break (0); + return NULL; + } + for (unsigned int i = 0; ikey.cipher) + { + GNUNET_break (0); + return NULL; + } + + csrh = GNUNET_new (struct TALER_EXCHANGE_CsRHandle); + csrh->exchange = exchange; + csrh->cb = res_cb; + csrh->cb_cls = res_cb_cls; + + csr_arr = json_array (); + GNUNET_assert (NULL != csr_arr); + for (unsigned int i = 0; inonce, + sizeof(struct TALER_CsNonce)), + GNUNET_JSON_pack_data_varsize ("denom_pub_hash", + &nk->pk->h_key, + sizeof(struct TALER_DenominationHash))); + GNUNET_assert (NULL != csr_obj); + GNUNET_assert (0 == + json_array_append_new (csr_arr, + csr_obj)); + } + csrh->url = TEAH_path_to_url (exchange, + "/csr"); + if (NULL == csrh->url) + { + json_decref (csr_arr); + GNUNET_free (csrh); + return NULL; + } + { + CURL *eh; + struct GNUNET_CURL_Context *ctx; + json_t *req; + + req = GNUNET_JSON_PACK ( + GNUNET_JSON_pack_array_steal ("nks", + csr_arr)); + ctx = TEAH_handle_to_context (exchange); + eh = TALER_EXCHANGE_curl_easy_get_ (csrh->url); + if ( (NULL == eh) || + (GNUNET_OK != + TALER_curl_easy_post (&csrh->post_ctx, + eh, + req)) ) + { + GNUNET_break (0); + if (NULL != eh) + curl_easy_cleanup (eh); + json_decref (req); + GNUNET_free (csrh->url); + GNUNET_free (csrh); + return NULL; + } + json_decref (req); + csrh->job = GNUNET_CURL_job_add2 (ctx, + eh, + csrh->post_ctx.headers, + &handle_csr_finished, + csrh); + } + return csrh; +} + + +void +TALER_EXCHANGE_csr_cancel (struct TALER_EXCHANGE_CsRHandle *csrh) +{ + if (NULL != csrh->job) + { + GNUNET_CURL_job_cancel (csrh->job); + csrh->job = NULL; + } + GNUNET_free (csrh->url); + TALER_curl_easy_post_finished (&csrh->post_ctx); + GNUNET_free (csrh); +} diff --git a/src/lib/exchange_api_deposit.c b/src/lib/exchange_api_deposit.c index 153f46505..2bfaaf6ce 100644 --- a/src/lib/exchange_api_deposit.c +++ b/src/lib/exchange_api_deposit.c @@ -461,6 +461,7 @@ handle_deposit_finished (void *cls, * @param amount the amount to be deposited * @param h_wire hash of the merchant’s account details * @param h_contract_terms hash of the contact of the merchant with the customer (further details are never disclosed to the exchange) + * @param ech hash over contract extensions * @param coin_pub coin’s public key * @param h_age_commitment coin’s hash of age commitment, might be NULL * @param denom_sig exchange’s unblinded signature of the coin @@ -552,7 +553,7 @@ TALER_EXCHANGE_deposit ( const struct TALER_Amount *amount, struct GNUNET_TIME_Timestamp wire_deadline, const char *merchant_payto_uri, - const struct TALER_WireSalt *wire_salt, + const struct TALER_WireSaltP *wire_salt, const struct TALER_PrivateContractHash *h_contract_terms, const struct TALER_AgeCommitmentHash *h_age_commitment, const json_t *extension_details, diff --git a/src/lib/exchange_api_deposits_get.c b/src/lib/exchange_api_deposits_get.c index 18fb9b7bd..30f3ee7f4 100644 --- a/src/lib/exchange_api_deposits_get.c +++ b/src/lib/exchange_api_deposits_get.c @@ -258,19 +258,6 @@ handle_deposit_wtid_finished (void *cls, } -/** - * Obtain wire transfer details about an existing deposit operation. - * - * @param exchange the exchange to query - * @param merchant_priv the merchant's private key - * @param h_wire hash of merchant's wire transfer details - * @param h_contract_terms hash of the proposal data from the contract - * between merchant and customer - * @param coin_pub public key of the coin - * @param cb function to call with the result - * @param cb_cls closure for @a cb - * @return handle to abort request - */ struct TALER_EXCHANGE_DepositGetHandle * TALER_EXCHANGE_deposits_get ( struct TALER_EXCHANGE_Handle *exchange, @@ -387,12 +374,6 @@ TALER_EXCHANGE_deposits_get ( } -/** - * Cancel /deposits/$WTID request. This function cannot be used on a request - * handle if a response is already served for it. - * - * @param dwh the wire deposits request handle - */ void TALER_EXCHANGE_deposits_get_cancel (struct TALER_EXCHANGE_DepositGetHandle *dwh) { diff --git a/src/lib/exchange_api_kyc_wallet.c b/src/lib/exchange_api_kyc_wallet.c index 4a41fd598..7a78ceb24 100644 --- a/src/lib/exchange_api_kyc_wallet.c +++ b/src/lib/exchange_api_kyc_wallet.c @@ -161,19 +161,11 @@ TALER_EXCHANGE_kyc_wallet (struct TALER_EXCHANGE_Handle *exchange, struct GNUNET_CURL_Context *ctx; struct TALER_ReservePublicKeyP reserve_pub; struct TALER_ReserveSignatureP reserve_sig; - struct GNUNET_CRYPTO_EccSignaturePurpose purpose = { - .size = htonl (sizeof (purpose)), - .purpose = htonl (TALER_SIGNATURE_WALLET_ACCOUNT_SETUP) - }; - /* FIXME: move to util/wallet-signatures.c! */ GNUNET_CRYPTO_eddsa_key_get_public (&reserve_priv->eddsa_priv, &reserve_pub.eddsa_pub); - - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_sign_ (&reserve_priv->eddsa_priv, - &purpose, - &reserve_sig.eddsa_signature)); + TALER_wallet_account_setup_sign (reserve_priv, + &reserve_sig); req = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("reserve_pub", &reserve_pub), diff --git a/src/lib/exchange_api_link.c b/src/lib/exchange_api_link.c index 9d801c38b..306ea9867 100644 --- a/src/lib/exchange_api_link.c +++ b/src/lib/exchange_api_link.c @@ -77,9 +77,7 @@ struct TALER_EXCHANGE_LinkHandle * @param json json reply with the data for one coin * @param coin_num number of the coin * @param trans_pub our transfer public key - * @param[out] coin_priv where to return private coin key - * @param[out] sig where to return private coin signature - * @param[out] pub where to return the public key for the coin + * @param[out] lci where to return coin details * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static enum GNUNET_GenericReturnValue @@ -87,27 +85,40 @@ parse_link_coin (const struct TALER_EXCHANGE_LinkHandle *lh, const json_t *json, uint32_t coin_num, const struct TALER_TransferPublicKeyP *trans_pub, - struct TALER_CoinSpendPrivateKeyP *coin_priv, - struct TALER_DenominationSignature *sig, - struct TALER_DenominationPublicKey *pub) + struct TALER_EXCHANGE_LinkedCoinInfo *lci) { struct TALER_BlindedDenominationSignature bsig; struct TALER_DenominationPublicKey rpub; struct TALER_CoinSpendSignatureP link_sig; + union TALER_DenominationBlindingKeyP bks; + struct TALER_ExchangeWithdrawValues alg_values; + struct TALER_CsNonce nonce; + uint32_t coin_idx; struct GNUNET_JSON_Specification spec[] = { TALER_JSON_spec_denom_pub ("denom_pub", &rpub), TALER_JSON_spec_blinded_denom_sig ("ev_sig", &bsig), + TALER_JSON_spec_exchange_withdraw_values ("ewv", + &alg_values), GNUNET_JSON_spec_fixed_auto ("link_sig", &link_sig), + GNUNET_JSON_spec_uint32 ("coin_idx", + &coin_idx), + GNUNET_JSON_spec_mark_optional ( + GNUNET_JSON_spec_fixed_auto ("cs_nonce", + &nonce)), GNUNET_JSON_spec_end () }; struct TALER_TransferSecretP secret; - struct TALER_PlanchetSecretsP fc; + struct TALER_PlanchetDetail pd; + struct TALER_CoinPubHash c_hash; struct TALER_AgeCommitmentHash h_age_commitment = {0}; // TODO, see below. /* parse reply */ + memset (&nonce, + 0, + sizeof (nonce)); if (GNUNET_OK != GNUNET_JSON_parse (json, spec, @@ -119,45 +130,56 @@ parse_link_coin (const struct TALER_EXCHANGE_LinkHandle *lh, TALER_link_recover_transfer_secret (trans_pub, &lh->coin_priv, &secret); - TALER_planchet_setup_refresh (&secret, - coin_num, - &fc); - + TALER_transfer_secret_to_planchet_secret (&secret, + coin_num, + &lci->ps); + TALER_planchet_setup_coin_priv (&lci->ps, + &alg_values, + &lci->coin_priv); + TALER_planchet_blinding_secret_create (&lci->ps, + &alg_values, + &bks); + if (GNUNET_OK != + TALER_planchet_prepare (&rpub, + &alg_values, + &bks, + &lci->coin_priv, + &c_hash, + &pd)) + { + GNUNET_break (0); + GNUNET_JSON_parse_free (spec); + return GNUNET_SYSERR; + } + if (TALER_DENOMINATION_CS == alg_values.cipher) + { + if (GNUNET_is_zero (&nonce)) + { + GNUNET_break_op (0); + GNUNET_JSON_parse_free (spec); + return GNUNET_SYSERR; + } + pd.blinded_planchet.details.cs_blinded_planchet.nonce = nonce; + } /* extract coin and signature */ if (GNUNET_OK != - TALER_denom_sig_unblind (sig, + TALER_denom_sig_unblind (&lci->sig, &bsig, - &fc.blinding_key, + &bks, + &c_hash, + &alg_values, &rpub)) { GNUNET_break_op (0); return GNUNET_SYSERR; } - *coin_priv = fc.coin_priv; /* verify link_sig */ { - struct TALER_PlanchetDetail pd; - struct TALER_CoinPubHash c_hash; struct TALER_CoinSpendPublicKeyP old_coin_pub; struct TALER_BlindedCoinHash coin_envelope_hash; GNUNET_CRYPTO_eddsa_key_get_public (&lh->coin_priv.eddsa_priv, &old_coin_pub.eddsa_pub); - if (GNUNET_OK != - TALER_planchet_prepare (&rpub, - &fc, - NULL, /* FIXME-oec. struct TALER_AgeCommitmentHash * */ - &c_hash, - &pd)) - { - GNUNET_break (0); - GNUNET_JSON_parse_free (spec); - return GNUNET_SYSERR; - } - GNUNET_CRYPTO_hash (pd.coin_ev, - pd.coin_ev_size, - &coin_envelope_hash.hash); - /* * TODO-oec: Derive the age commitment vector and hash it into * h_age_commitment. @@ -167,6 +189,9 @@ parse_link_coin (const struct TALER_EXCHANGE_LinkHandle *lh, * - Where do we get the information bout the previous coin's age groups? */ + TALER_coin_ev_hash (&pd.blinded_planchet, + &pd.denom_pub_hash, + &coin_envelope_hash); if (GNUNET_OK != TALER_wallet_link_verify (&pd.denom_pub_hash, trans_pub, @@ -176,15 +201,15 @@ parse_link_coin (const struct TALER_EXCHANGE_LinkHandle *lh, &link_sig)) { GNUNET_break_op (0); - GNUNET_free (pd.coin_ev); + TALER_blinded_planchet_free (&pd.blinded_planchet); GNUNET_JSON_parse_free (spec); return GNUNET_SYSERR; } - GNUNET_free (pd.coin_ev); + TALER_blinded_planchet_free (&pd.blinded_planchet); } /* clean up */ - TALER_denom_pub_deep_copy (pub, + TALER_denom_pub_deep_copy (&lci->pub, &rpub); GNUNET_JSON_parse_free (spec); return GNUNET_OK; @@ -206,9 +231,9 @@ parse_link_ok (struct TALER_EXCHANGE_LinkHandle *lh, unsigned int session; unsigned int num_coins; int ret; - struct TALER_EXCHANGE_HttpResponse hr = { - .reply = json, - .http_status = MHD_HTTP_OK + struct TALER_EXCHANGE_LinkResult lr = { + .hr.reply = json, + .hr.http_status = MHD_HTTP_OK }; if (! json_is_array (json)) @@ -261,12 +286,9 @@ parse_link_ok (struct TALER_EXCHANGE_LinkHandle *lh, { unsigned int off_coin; /* index into 1d array */ unsigned int i; - struct TALER_CoinSpendPrivateKeyP coin_privs[GNUNET_NZL (num_coins)]; - struct TALER_DenominationSignature sigs[GNUNET_NZL (num_coins)]; - struct TALER_DenominationPublicKey pubs[GNUNET_NZL (num_coins)]; + struct TALER_EXCHANGE_LinkedCoinInfo lcis[GNUNET_NZL (num_coins)]; - memset (sigs, 0, sizeof (sigs)); - memset (pubs, 0, sizeof (pubs)); + memset (lcis, 0, sizeof (lcis)); off_coin = 0; for (session = 0; sessionlink_cb (lh->link_cb_cls, - &hr, - num_coins, - coin_privs, - sigs, - pubs); + &lr); lh->link_cb = NULL; ret = GNUNET_OK; } @@ -347,8 +368,8 @@ parse_link_ok (struct TALER_EXCHANGE_LinkHandle *lh, GNUNET_assert (off_coin <= num_coins); for (i = 0; ijob = NULL; switch (response_code) { case 0: - hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; + lr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; break; case MHD_HTTP_OK: if (GNUNET_OK != @@ -387,49 +408,45 @@ handle_link_finished (void *cls, j)) { GNUNET_break_op (0); - hr.http_status = 0; - hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; + lr.hr.http_status = 0; + lr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; break; } GNUNET_assert (NULL == lh->link_cb); TALER_EXCHANGE_link_cancel (lh); return; case MHD_HTTP_BAD_REQUEST: - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + lr.hr.ec = TALER_JSON_get_error_code (j); + lr.hr.hint = TALER_JSON_get_error_hint (j); /* This should never happen, either us or the exchange is buggy (or API version conflict); just pass JSON reply to the application */ break; case MHD_HTTP_NOT_FOUND: - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + lr.hr.ec = TALER_JSON_get_error_code (j); + lr.hr.hint = TALER_JSON_get_error_hint (j); /* Nothing really to verify, exchange says this coin was not melted; we should pass the JSON reply to the application */ break; case MHD_HTTP_INTERNAL_SERVER_ERROR: - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + lr.hr.ec = TALER_JSON_get_error_code (j); + lr.hr.hint = TALER_JSON_get_error_hint (j); /* Server had an internal issue; we should retry, but this API leaves this to the application */ break; default: /* unexpected response code */ GNUNET_break_op (0); - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + lr.hr.ec = TALER_JSON_get_error_code (j); + lr.hr.hint = TALER_JSON_get_error_hint (j); GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected response code %u/%d for exchange link\n", (unsigned int) response_code, - (int) hr.ec); + (int) lr.hr.ec); break; } if (NULL != lh->link_cb) lh->link_cb (lh->link_cb_cls, - &hr, - 0, - NULL, - NULL, - NULL); + &lr); TALER_EXCHANGE_link_cancel (lh); } diff --git a/src/lib/exchange_api_management_get_keys.c b/src/lib/exchange_api_management_get_keys.c index 1b6e0db8c..ac419388f 100644 --- a/src/lib/exchange_api_management_get_keys.c +++ b/src/lib/exchange_api_management_get_keys.c @@ -92,6 +92,8 @@ handle_ok (struct TALER_EXCHANGE_ManagementGetKeysHandle *gh, &fk.master_pub), GNUNET_JSON_spec_fixed_auto ("denom_secmod_public_key", &fk.denom_secmod_public_key), + GNUNET_JSON_spec_fixed_auto ("denom_secmod_cs_public_key", + &fk.denom_secmod_cs_public_key), GNUNET_JSON_spec_fixed_auto ("signkey_secmod_public_key", &fk.signkey_secmod_public_key), GNUNET_JSON_spec_end () @@ -243,6 +245,26 @@ handle_ok (struct TALER_EXCHANGE_ManagementGetKeysHandle *gh, } } break; + case TALER_DENOMINATION_CS: + { + struct TALER_CsPubHashP h_cs; + + TALER_cs_pub_hash (&denom_key->key.details.cs_public_key, + &h_cs); + if (GNUNET_OK != + TALER_exchange_secmod_cs_verify (&h_cs, + section_name, + denom_key->valid_from, + duration, + &fk.denom_secmod_cs_public_key, + &denom_key->denom_secmod_sig)) + { + GNUNET_break_op (0); + ok = false; + break; + } + } + break; default: GNUNET_break_op (0); ok = false; diff --git a/src/lib/exchange_api_melt.c b/src/lib/exchange_api_melt.c index f375171b9..18596d891 100644 --- a/src/lib/exchange_api_melt.c +++ b/src/lib/exchange_api_melt.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2015-2021 Taler Systems SA + Copyright (C) 2015-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -73,7 +73,28 @@ struct TALER_EXCHANGE_MeltHandle /** * Actual information about the melt operation. */ - struct MeltData *md; + struct MeltData md; + + /** + * The secret the entire melt operation is seeded from. + */ + struct TALER_RefreshMasterSecretP rms; + + /** + * Details about the characteristics of the requested melt operation. + */ + const struct TALER_EXCHANGE_RefreshData *rd; + + /** + * Array of `num_fresh_coins` per-coin values + * returned from melt operation. + */ + struct TALER_EXCHANGE_MeltBlindingDetail *mbds; + + /** + * Handle for the preflight request, or NULL. + */ + struct TALER_EXCHANGE_CsRHandle *csr; /** * Public key of the coin being melted. @@ -83,7 +104,13 @@ struct TALER_EXCHANGE_MeltHandle /** * @brief Public information about the coin's denomination key */ - struct TALER_EXCHANGE_DenomPublicKey dki; + const struct TALER_EXCHANGE_DenomPublicKey *dki; + + /** + * Gamma value chosen by the exchange during melt. + */ + uint32_t noreveal_index; + }; @@ -91,27 +118,27 @@ struct TALER_EXCHANGE_MeltHandle * Verify that the signature on the "200 OK" response * from the exchange is valid. * - * @param mh melt handle + * @param[in,out] mh melt handle * @param json json reply with the signature * @param[out] exchange_pub public key of the exchange used for the signature - * @param[out] noreveal_index set to the noreveal index selected by the exchange * @return #GNUNET_OK if the signature is valid, #GNUNET_SYSERR if not */ static enum GNUNET_GenericReturnValue verify_melt_signature_ok (struct TALER_EXCHANGE_MeltHandle *mh, const json_t *json, - struct TALER_ExchangePublicKeyP *exchange_pub, - uint32_t *noreveal_index) + struct TALER_ExchangePublicKeyP *exchange_pub) { struct TALER_ExchangeSignatureP exchange_sig; const struct TALER_EXCHANGE_Keys *key_state; struct GNUNET_JSON_Specification spec[] = { - GNUNET_JSON_spec_fixed_auto ("exchange_sig", &exchange_sig), - GNUNET_JSON_spec_fixed_auto ("exchange_pub", exchange_pub), - GNUNET_JSON_spec_uint32 ("noreveal_index", noreveal_index), + GNUNET_JSON_spec_fixed_auto ("exchange_sig", + &exchange_sig), + GNUNET_JSON_spec_fixed_auto ("exchange_pub", + exchange_pub), + GNUNET_JSON_spec_uint32 ("noreveal_index", + &mh->noreveal_index), GNUNET_JSON_spec_end () }; - struct TALER_RefreshMeltConfirmationPS confirm; if (GNUNET_OK != GNUNET_JSON_parse (json, @@ -121,7 +148,6 @@ verify_melt_signature_ok (struct TALER_EXCHANGE_MeltHandle *mh, GNUNET_break_op (0); return GNUNET_SYSERR; } - /* check that exchange signing key is permitted */ key_state = TALER_EXCHANGE_get_keys (mh->exchange); if (GNUNET_OK != @@ -133,23 +159,18 @@ verify_melt_signature_ok (struct TALER_EXCHANGE_MeltHandle *mh, } /* check that noreveal index is in permitted range */ - if (TALER_CNC_KAPPA <= *noreveal_index) + if (TALER_CNC_KAPPA <= mh->noreveal_index) { GNUNET_break_op (0); return GNUNET_SYSERR; } - /* verify signature by exchange */ - confirm.purpose.purpose = htonl (TALER_SIGNATURE_EXCHANGE_CONFIRM_MELT); - confirm.purpose.size - = htonl (sizeof (struct TALER_RefreshMeltConfirmationPS)); - confirm.rc = mh->md->rc; - confirm.noreveal_index = htonl (*noreveal_index); if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_EXCHANGE_CONFIRM_MELT, - &confirm, - &exchange_sig.eddsa_signature, - &exchange_pub->eddsa_pub)) + TALER_exchange_melt_confirmation_verify ( + &mh->md.rc, + mh->noreveal_index, + exchange_pub, + &exchange_sig)) { GNUNET_break_op (0); return GNUNET_SYSERR; @@ -182,8 +203,8 @@ verify_melt_signature_denom_conflict (struct TALER_EXCHANGE_MeltHandle *mh, history = json_object_get (json, "history"); if (GNUNET_OK != - TALER_EXCHANGE_verify_coin_history (&mh->dki, - mh->dki.value.currency, + TALER_EXCHANGE_verify_coin_history (mh->dki, + mh->dki->value.currency, &mh->coin_pub, history, &h_denom_pub, @@ -192,7 +213,7 @@ verify_melt_signature_denom_conflict (struct TALER_EXCHANGE_MeltHandle *mh, GNUNET_break_op (0); return GNUNET_SYSERR; } - if (0 != GNUNET_memcmp (&mh->dki.h_key, + if (0 != GNUNET_memcmp (&mh->dki->h_key, &h_denom_pub)) return GNUNET_OK; /* indeed, proof with different denomination key provided */ /* invalid proof provided */ @@ -234,7 +255,7 @@ verify_melt_signature_spend_conflict (struct TALER_EXCHANGE_MeltHandle *mh, } /* Find out which coin was deemed problematic by the exchange */ - mc = &mh->md->melted_coin; + mc = &mh->md.melted_coin; /* verify coin history */ memset (&h_denom_pub, 0, @@ -242,7 +263,7 @@ verify_melt_signature_spend_conflict (struct TALER_EXCHANGE_MeltHandle *mh, history = json_object_get (json, "history"); if (GNUNET_OK != - TALER_EXCHANGE_verify_coin_history (&mh->dki, + TALER_EXCHANGE_verify_coin_history (mh->dki, mc->original_value.currency, &mh->coin_pub, history, @@ -281,7 +302,7 @@ verify_melt_signature_spend_conflict (struct TALER_EXCHANGE_MeltHandle *mh, /* everything OK, valid proof of double-spending was provided */ return GNUNET_OK; case TALER_EC_EXCHANGE_GENERIC_COIN_CONFLICTING_DENOMINATION_KEY: - if (0 != GNUNET_memcmp (&mh->dki.h_key, + if (0 != GNUNET_memcmp (&mh->dki->h_key, &h_denom_pub)) return GNUNET_OK; /* indeed, proof with different denomination key provided */ /* invalid proof provided */ @@ -309,51 +330,45 @@ handle_melt_finished (void *cls, const void *response) { struct TALER_EXCHANGE_MeltHandle *mh = cls; - uint32_t noreveal_index = TALER_CNC_KAPPA; /* invalid value */ - struct TALER_ExchangePublicKeyP exchange_pub; const json_t *j = response; - struct TALER_EXCHANGE_HttpResponse hr = { - .reply = j, - .http_status = (unsigned int) response_code + struct TALER_EXCHANGE_MeltResponse mr = { + .hr.reply = j, + .hr.http_status = (unsigned int) response_code }; mh->job = NULL; switch (response_code) { case 0: - hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; + mr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; break; case MHD_HTTP_OK: if (GNUNET_OK != verify_melt_signature_ok (mh, j, - &exchange_pub, - &noreveal_index)) + &mr.details.success.sign_key)) { GNUNET_break_op (0); - hr.http_status = 0; - hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; - } - if (NULL != mh->melt_cb) - { - mh->melt_cb (mh->melt_cb_cls, - &hr, - noreveal_index, - (0 == hr.http_status) - ? NULL - : &exchange_pub); - mh->melt_cb = NULL; + mr.hr.http_status = 0; + mr.hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; + break; } + mr.details.success.noreveal_index = mh->noreveal_index; + mr.details.success.num_mbds = mh->rd->fresh_pks_len; + mr.details.success.mbds = mh->mbds; + mh->melt_cb (mh->melt_cb_cls, + &mr); + mh->melt_cb = NULL; break; case MHD_HTTP_BAD_REQUEST: /* This should never happen, either us or the exchange is buggy (or API version conflict); just pass JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.ec = TALER_JSON_get_error_code (j); + mr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_CONFLICT: - hr.ec = TALER_JSON_get_error_code (j); - switch (hr.ec) + mr.hr.ec = TALER_JSON_get_error_code (j); + switch (mr.hr.ec) { case TALER_EC_EXCHANGE_GENERIC_INSUFFICIENT_FUNDS: /* Double spending; check signatures on transaction history */ @@ -362,9 +377,9 @@ handle_melt_finished (void *cls, j)) { GNUNET_break_op (0); - hr.http_status = 0; - hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.http_status = 0; + mr.hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; + mr.hr.hint = TALER_JSON_get_error_hint (j); } break; case TALER_EC_EXCHANGE_GENERIC_COIN_CONFLICTING_DENOMINATION_KEY: @@ -373,16 +388,16 @@ handle_melt_finished (void *cls, j)) { GNUNET_break_op (0); - hr.http_status = 0; - hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.http_status = 0; + mr.hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; + mr.hr.hint = TALER_JSON_get_error_hint (j); } break; default: GNUNET_break_op (0); - hr.http_status = 0; - hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.http_status = 0; + mr.hr.ec = TALER_EC_EXCHANGE_MELT_INVALID_SIGNATURE_BY_EXCHANGE; + mr.hr.hint = TALER_JSON_get_error_hint (j); break; } break; @@ -390,95 +405,96 @@ handle_melt_finished (void *cls, /* Nothing really to verify, exchange says one of the signatures is invalid; assuming we checked them, this should never happen, we should pass the JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.ec = TALER_JSON_get_error_code (j); + mr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_NOT_FOUND: /* Nothing really to verify, this should never happen, we should pass the JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.ec = TALER_JSON_get_error_code (j); + mr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_INTERNAL_SERVER_ERROR: /* Server had an internal issue; we should retry, but this API leaves this to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.ec = TALER_JSON_get_error_code (j); + mr.hr.hint = TALER_JSON_get_error_hint (j); break; default: /* unexpected response code */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + mr.hr.ec = TALER_JSON_get_error_code (j); + mr.hr.hint = TALER_JSON_get_error_hint (j); GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected response code %u/%d for exchange melt\n", (unsigned int) response_code, - hr.ec); + mr.hr.ec); GNUNET_break_op (0); break; } if (NULL != mh->melt_cb) mh->melt_cb (mh->melt_cb_cls, - &hr, - UINT32_MAX, - NULL); + &mr); TALER_EXCHANGE_melt_cancel (mh); } -struct TALER_EXCHANGE_MeltHandle * -TALER_EXCHANGE_melt (struct TALER_EXCHANGE_Handle *exchange, - const json_t *refresh_data, - TALER_EXCHANGE_MeltCallback melt_cb, - void *melt_cb_cls) +/** + * Start the actual melt operation, now that we have + * the exchange's input values. + * + * @param[in,out] mh melt operation to run + * @return #GNUNET_OK if we could start the operation + */ +static enum GNUNET_GenericReturnValue +start_melt (struct TALER_EXCHANGE_MeltHandle *mh) { const struct TALER_EXCHANGE_Keys *key_state; - const struct TALER_EXCHANGE_DenomPublicKey *dki; json_t *melt_obj; - struct TALER_EXCHANGE_MeltHandle *mh; CURL *eh; struct GNUNET_CURL_Context *ctx; - struct MeltData *md; struct TALER_CoinSpendSignatureP confirm_sig; char arg_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2 + 32]; struct TALER_DenominationHash h_denom_pub; - struct TALER_CoinSpendPublicKeyP coin_pub; + struct TALER_ExchangeWithdrawValues alg_values[mh->rd->fresh_pks_len]; - GNUNET_assert (GNUNET_YES == - TEAH_handle_is_ready (exchange)); - md = TALER_EXCHANGE_deserialize_melt_data_ (refresh_data, - exchange->key_data.currency); - if (NULL == md) + for (unsigned int i = 0; ird->fresh_pks_len; i++) + alg_values[i] = mh->mbds[i].alg_value; + if (GNUNET_OK != + TALER_EXCHANGE_get_melt_data_ (&mh->rms, + mh->rd, + alg_values, + &mh->md)) { GNUNET_break (0); - return NULL; + return GNUNET_SYSERR; } - TALER_denom_pub_hash (&md->melted_coin.pub_key, + TALER_denom_pub_hash (&mh->md.melted_coin.pub_key, &h_denom_pub); - TALER_wallet_melt_sign (&md->melted_coin.melt_amount_with_fee, - &md->melted_coin.fee_melt, - &md->rc, + TALER_wallet_melt_sign (&mh->md.melted_coin.melt_amount_with_fee, + &mh->md.melted_coin.fee_melt, + &mh->md.rc, &h_denom_pub, - &md->melted_coin.coin_priv, + &mh->md.melted_coin.coin_priv, &confirm_sig); - GNUNET_CRYPTO_eddsa_key_get_public (&md->melted_coin.coin_priv.eddsa_priv, - &coin_pub.eddsa_pub); + GNUNET_CRYPTO_eddsa_key_get_public (&mh->md.melted_coin.coin_priv.eddsa_priv, + &mh->coin_pub.eddsa_pub); melt_obj = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("denom_pub_hash", &h_denom_pub), TALER_JSON_pack_denom_sig ("denom_sig", - &md->melted_coin.sig), + &mh->md.melted_coin.sig), GNUNET_JSON_pack_data_auto ("confirm_sig", &confirm_sig), TALER_JSON_pack_amount ("value_with_fee", - &md->melted_coin.melt_amount_with_fee), + &mh->md.melted_coin.melt_amount_with_fee), GNUNET_JSON_pack_data_auto ("rc", - &md->rc)); + &mh->md.rc)); { char pub_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2]; char *end; end = GNUNET_STRINGS_data_to_string ( - &coin_pub, + &mh->coin_pub, sizeof (struct TALER_CoinSpendPublicKeyP), pub_str, sizeof (pub_str)); @@ -489,29 +505,19 @@ TALER_EXCHANGE_melt (struct TALER_EXCHANGE_Handle *exchange, pub_str); } - key_state = TALER_EXCHANGE_get_keys (exchange); - dki = TALER_EXCHANGE_get_denomination_key (key_state, - &md->melted_coin.pub_key); + ctx = TEAH_handle_to_context (mh->exchange); + key_state = TALER_EXCHANGE_get_keys (mh->exchange); + mh->dki = TALER_EXCHANGE_get_denomination_key (key_state, + &mh->md.melted_coin.pub_key); /* and now we can at last begin the actual request handling */ - mh = GNUNET_new (struct TALER_EXCHANGE_MeltHandle); - mh->exchange = exchange; - mh->coin_pub = coin_pub; - mh->dki = *dki; - memset (&mh->dki.key, - 0, - sizeof (mh->dki.key)); /* lifetime not warranted, so better - not copy the pointers */ - mh->melt_cb = melt_cb; - mh->melt_cb_cls = melt_cb_cls; - mh->md = md; - mh->url = TEAH_path_to_url (exchange, + + mh->url = TEAH_path_to_url (mh->exchange, arg_str); if (NULL == mh->url) { json_decref (melt_obj); - GNUNET_free (mh); - return NULL; + return GNUNET_SYSERR; } eh = TALER_EXCHANGE_curl_easy_get_ (mh->url); if ( (NULL == eh) || @@ -524,17 +530,173 @@ TALER_EXCHANGE_melt (struct TALER_EXCHANGE_Handle *exchange, if (NULL != eh) curl_easy_cleanup (eh); json_decref (melt_obj); - GNUNET_free (mh->url); - GNUNET_free (mh); - return NULL; + return GNUNET_SYSERR; } json_decref (melt_obj); - ctx = TEAH_handle_to_context (exchange); mh->job = GNUNET_CURL_job_add2 (ctx, eh, mh->ctx.headers, &handle_melt_finished, mh); + return GNUNET_OK; +} + + +/** + * The melt request @a mh failed, return an error to + * the application and cancel the operation. + * + * @param[in] mh melt request that failed + */ +static void +fail_mh (struct TALER_EXCHANGE_MeltHandle *mh, + enum TALER_ErrorCode ec) +{ + struct TALER_EXCHANGE_MeltResponse mr = { + .hr.ec = ec + }; + + mh->melt_cb (mh->melt_cb_cls, + &mr); + TALER_EXCHANGE_melt_cancel (mh); +} + + +/** + * Callbacks of this type are used to serve the result of submitting a + * CS R request to a exchange. + * + * @param cls closure with our `struct TALER_EXCHANGE_MeltHandle *` + * @param csrr response details + */ +static void +csr_cb (void *cls, + const struct TALER_EXCHANGE_CsRResponse *csrr) +{ + struct TALER_EXCHANGE_MeltHandle *mh = cls; + unsigned int nks_off = 0; + + mh->csr = NULL; + if (MHD_HTTP_OK != csrr->hr.http_status) + { + struct TALER_EXCHANGE_MeltResponse mr = { + .hr = csrr->hr + }; + + mr.hr.hint = "/csr failed"; + mh->melt_cb (mh->melt_cb_cls, + &mr); + TALER_EXCHANGE_melt_cancel (mh); + return; + } + for (unsigned int i = 0; ird->fresh_pks_len; i++) + { + const struct TALER_EXCHANGE_DenomPublicKey *fresh_pk = + &mh->rd->fresh_pks[i]; + struct TALER_ExchangeWithdrawValues *wv = &mh->mbds[i].alg_value; + + switch (fresh_pk->key.cipher) + { + case TALER_DENOMINATION_INVALID: + GNUNET_break (0); + fail_mh (mh, + TALER_EC_GENERIC_CLIENT_INTERNAL_ERROR); + return; + case TALER_DENOMINATION_RSA: + GNUNET_assert (TALER_DENOMINATION_RSA == wv->cipher); + break; + case TALER_DENOMINATION_CS: + GNUNET_assert (TALER_DENOMINATION_CS == wv->cipher); + *wv = csrr->details.success.alg_values[nks_off]; + nks_off++; + break; + } + } + if (GNUNET_OK != + start_melt (mh)) + { + GNUNET_break (0); + fail_mh (mh, + TALER_EC_GENERIC_CLIENT_INTERNAL_ERROR); + return; + } +} + + +struct TALER_EXCHANGE_MeltHandle * +TALER_EXCHANGE_melt (struct TALER_EXCHANGE_Handle *exchange, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, + TALER_EXCHANGE_MeltCallback melt_cb, + void *melt_cb_cls) +{ + struct TALER_EXCHANGE_NonceKey nks[GNUNET_NZL (rd->fresh_pks_len)]; + unsigned int nks_off = 0; + struct TALER_EXCHANGE_MeltHandle *mh; + + if (0 == rd->fresh_pks_len) + { + GNUNET_break (0); + return NULL; + } + GNUNET_assert (GNUNET_YES == + TEAH_handle_is_ready (exchange)); + mh = GNUNET_new (struct TALER_EXCHANGE_MeltHandle); + mh->noreveal_index = TALER_CNC_KAPPA; /* invalid value */ + mh->exchange = exchange; + mh->rd = rd; + mh->rms = *rms; + mh->melt_cb = melt_cb; + mh->melt_cb_cls = melt_cb_cls; + mh->mbds = GNUNET_new_array (rd->fresh_pks_len, + struct TALER_EXCHANGE_MeltBlindingDetail); + for (unsigned int i = 0; ifresh_pks_len; i++) + { + const struct TALER_EXCHANGE_DenomPublicKey *fresh_pk = &rd->fresh_pks[i]; + struct TALER_ExchangeWithdrawValues *wv = &mh->mbds[i].alg_value; + + switch (fresh_pk->key.cipher) + { + case TALER_DENOMINATION_INVALID: + GNUNET_break (0); + GNUNET_free (mh->mbds); + GNUNET_free (mh); + return NULL; + case TALER_DENOMINATION_RSA: + wv->cipher = TALER_DENOMINATION_RSA; + break; + case TALER_DENOMINATION_CS: + wv->cipher = TALER_DENOMINATION_CS; + nks[nks_off].pk = fresh_pk; + TALER_cs_refresh_nonce_derive (rms, + i, + &nks[nks_off].nonce); + nks_off++; + break; + } + } + if (0 != nks_off) + { + mh->csr = TALER_EXCHANGE_csr (exchange, + nks_off, + nks, + &csr_cb, + mh); + if (NULL == mh->csr) + { + GNUNET_break (0); + TALER_EXCHANGE_melt_cancel (mh); + return NULL; + } + return mh; + } + if (GNUNET_OK != + start_melt (mh)) + { + GNUNET_break (0); + TALER_EXCHANGE_melt_cancel (mh); + return NULL; + } return mh; } @@ -547,8 +709,13 @@ TALER_EXCHANGE_melt_cancel (struct TALER_EXCHANGE_MeltHandle *mh) GNUNET_CURL_job_cancel (mh->job); mh->job = NULL; } - TALER_EXCHANGE_free_melt_data_ (mh->md); /* does not free 'md' itself */ - GNUNET_free (mh->md); + if (NULL != mh->csr) + { + TALER_EXCHANGE_csr_cancel (mh->csr); + mh->csr = NULL; + } + TALER_EXCHANGE_free_melt_data_ (&mh->md); /* does not free 'md' itself */ + GNUNET_free (mh->mbds); GNUNET_free (mh->url); TALER_curl_easy_post_finished (&mh->ctx); GNUNET_free (mh); diff --git a/src/lib/exchange_api_recoup.c b/src/lib/exchange_api_recoup.c index 10f74ce65..9b7201cd0 100644 --- a/src/lib/exchange_api_recoup.c +++ b/src/lib/exchange_api_recoup.c @@ -206,7 +206,7 @@ handle_recoup_finished (void *cls, exchange is here. We should look at the key structure of ph->exchange, and find the smallest _currently withdrawable_ denomination and check - if the value remaining would suffice... */// + if the value remaining would suffice... */ GNUNET_break_op (0); hr.http_status = 0; hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; @@ -284,7 +284,8 @@ struct TALER_EXCHANGE_RecoupHandle * TALER_EXCHANGE_recoup (struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_DenominationSignature *denom_sig, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *exchange_vals, + const struct TALER_PlanchetMasterSecretP *ps, TALER_EXCHANGE_RecoupResultCallback recoup_cb, void *recoup_cb_cls) { @@ -296,26 +297,55 @@ TALER_EXCHANGE_recoup (struct TALER_EXCHANGE_Handle *exchange, json_t *recoup_obj; CURL *eh; char arg_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2 + 32]; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; GNUNET_assert (GNUNET_YES == TEAH_handle_is_ready (exchange)); - GNUNET_CRYPTO_eddsa_key_get_public (&ps->coin_priv.eddsa_priv, + + TALER_planchet_setup_coin_priv (ps, + exchange_vals, + &coin_priv); + TALER_planchet_blinding_secret_create (ps, + exchange_vals, + &bks); + GNUNET_CRYPTO_eddsa_key_get_public (&coin_priv.eddsa_priv, &coin_pub.eddsa_pub); TALER_denom_pub_hash (&pk->key, &h_denom_pub); TALER_wallet_recoup_sign (&h_denom_pub, - &ps->blinding_key, - &ps->coin_priv, + &bks, + &coin_priv, &coin_sig); recoup_obj = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("denom_pub_hash", &h_denom_pub), TALER_JSON_pack_denom_sig ("denom_sig", denom_sig), + TALER_JSON_pack_exchange_withdraw_values ("ewv", + exchange_vals), GNUNET_JSON_pack_data_auto ("coin_sig", &coin_sig), GNUNET_JSON_pack_data_auto ("coin_blind_key_secret", - &ps->blinding_key)); + &bks)); + if (TALER_DENOMINATION_CS == denom_sig->cipher) + { + struct TALER_CsNonce nonce; + + // FIXME: add this to the spec! + /* NOTE: this is not elegant, and as per the note in TALER_coin_ev_hash() + it is not strictly clear that the nonce is needed. Best case would be + to find a way to include it more 'naturally' somehow, for example with + the variant union version of bks! */ + TALER_cs_withdraw_nonce_derive (ps, + &nonce); + GNUNET_assert ( + 0 == + json_object_set_new (recoup_obj, + "cs_nonce", + GNUNET_JSON_from_data_auto ( + &nonce))); + } { char pub_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2]; diff --git a/src/lib/exchange_api_recoup_refresh.c b/src/lib/exchange_api_recoup_refresh.c index 03f756646..02e994155 100644 --- a/src/lib/exchange_api_recoup_refresh.c +++ b/src/lib/exchange_api_recoup_refresh.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2017-2021 Taler Systems SA + Copyright (C) 2017-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -165,6 +165,19 @@ handle_recoup_refresh_finished (void *cls, hr.ec = TALER_JSON_get_error_code (j); hr.hint = TALER_JSON_get_error_hint (j); break; + case MHD_HTTP_FORBIDDEN: + /* Nothing really to verify, exchange says one of the signatures is + invalid; as we checked them, this should never happen, we + should pass the JSON reply to the application */ + hr.ec = TALER_JSON_get_error_code (j); + hr.hint = TALER_JSON_get_error_hint (j); + break; + case MHD_HTTP_NOT_FOUND: + /* Nothing really to verify, this should never + happen, we should pass the JSON reply to the application */ + hr.ec = TALER_JSON_get_error_code (j); + hr.hint = TALER_JSON_get_error_hint (j); + break; case MHD_HTTP_CONFLICT: { /* Insufficient funds, proof attached */ @@ -238,19 +251,6 @@ handle_recoup_refresh_finished (void *cls, TALER_EXCHANGE_recoup_refresh_cancel (ph); return; } - case MHD_HTTP_FORBIDDEN: - /* Nothing really to verify, exchange says one of the signatures is - invalid; as we checked them, this should never happen, we - should pass the JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); - break; - case MHD_HTTP_NOT_FOUND: - /* Nothing really to verify, this should never - happen, we should pass the JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); - break; case MHD_HTTP_GONE: /* Kind of normal: the money was already sent to the merchant (it was too late for the refund). */ @@ -286,7 +286,10 @@ TALER_EXCHANGE_recoup_refresh ( struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_DenominationSignature *denom_sig, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *exchange_vals, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_PlanchetMasterSecretP *ps, + unsigned int idx, TALER_EXCHANGE_RecoupRefreshResultCallback recoup_cb, void *recoup_cb_cls) { @@ -298,26 +301,57 @@ TALER_EXCHANGE_recoup_refresh ( json_t *recoup_obj; CURL *eh; char arg_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2 + 32]; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; + GNUNET_assert (NULL != recoup_cb); GNUNET_assert (GNUNET_YES == TEAH_handle_is_ready (exchange)); - GNUNET_CRYPTO_eddsa_key_get_public (&ps->coin_priv.eddsa_priv, + TALER_planchet_setup_coin_priv (ps, + exchange_vals, + &coin_priv); + TALER_planchet_blinding_secret_create (ps, + exchange_vals, + &bks); + GNUNET_CRYPTO_eddsa_key_get_public (&coin_priv.eddsa_priv, &coin_pub.eddsa_pub); TALER_denom_pub_hash (&pk->key, &h_denom_pub); TALER_wallet_recoup_refresh_sign (&h_denom_pub, - &ps->blinding_key, - &ps->coin_priv, + &bks, + &coin_priv, &coin_sig); recoup_obj = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("denom_pub_hash", &h_denom_pub), TALER_JSON_pack_denom_sig ("denom_sig", denom_sig), + TALER_JSON_pack_exchange_withdraw_values ("ewv", + exchange_vals), GNUNET_JSON_pack_data_auto ("coin_sig", &coin_sig), GNUNET_JSON_pack_data_auto ("coin_blind_key_secret", - &ps->blinding_key)); + &bks)); + + if (TALER_DENOMINATION_CS == denom_sig->cipher) + { + struct TALER_CsNonce nonce; + + // FIXME: add this to the spec! + /* NOTE: this is not elegant, and as per the note in TALER_coin_ev_hash() + it is not strictly clear that the nonce is needed. Best case would be + to find a way to include it more 'naturally' somehow, for example with + the variant union version of bks! */ + TALER_cs_refresh_nonce_derive (rms, + idx, + &nonce); + GNUNET_assert ( + 0 == + json_object_set_new (recoup_obj, + "cs_nonce", + GNUNET_JSON_from_data_auto ( + &nonce))); + } { char pub_str[sizeof (struct TALER_CoinSpendPublicKeyP) * 2]; diff --git a/src/lib/exchange_api_refresh_common.c b/src/lib/exchange_api_refresh_common.c index ece9fe94f..5f8152e1a 100644 --- a/src/lib/exchange_api_refresh_common.c +++ b/src/lib/exchange_api_refresh_common.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2015-2021 Taler Systems SA + Copyright (C) 2015-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -23,498 +23,187 @@ #include "exchange_api_refresh_common.h" -/** - * Free all information associated with a melted coin session. - * - * @param mc melted coin to release, the pointer itself is NOT - * freed (as it is typically not allocated by itself) - */ -static void -free_melted_coin (struct MeltedCoin *mc) -{ - TALER_denom_pub_free (&mc->pub_key); - TALER_denom_sig_free (&mc->sig); -} - - void TALER_EXCHANGE_free_melt_data_ (struct MeltData *md) { - free_melted_coin (&md->melted_coin); - if (NULL != md->fresh_pks) + for (unsigned int i = 0; i < TALER_CNC_KAPPA; i++) { - for (unsigned int i = 0; inum_fresh_coins; i++) - TALER_denom_pub_free (&md->fresh_pks[i]); - GNUNET_free (md->fresh_pks); + struct TALER_RefreshCoinData *rcds = md->rcd[i]; + + if (NULL == rcds) + continue; + for (unsigned int j = 0; j < md->num_fresh_coins; j++) + TALER_blinded_planchet_free (&rcds[j].blinded_planchet); + GNUNET_free (rcds); + } + TALER_denom_pub_free (&md->melted_coin.pub_key); + TALER_denom_sig_free (&md->melted_coin.sig); + if (NULL != md->fcds) + { + for (unsigned int j = 0; jnum_fresh_coins; j++) + { + struct FreshCoinData *fcd = &md->fcds[j]; + + TALER_denom_pub_free (&fcd->fresh_pk); + } + GNUNET_free (md->fcds); } - for (unsigned int i = 0; ifresh_coins[i]); /* Finally, clean up a bit... */ GNUNET_CRYPTO_zero_keys (md, sizeof (struct MeltData)); } -/** - * Serialize information about a coin we are melting. - * - * @param mc information to serialize - * @return NULL on error - */ -static json_t * -serialize_melted_coin (const struct MeltedCoin *mc) +enum GNUNET_GenericReturnValue +TALER_EXCHANGE_get_melt_data_ ( + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, + const struct TALER_ExchangeWithdrawValues *alg_values, + struct MeltData *md) { - json_t *tprivs; - - tprivs = json_array (); - GNUNET_assert (NULL != tprivs); - for (unsigned int i = 0; itransfer_priv[i])))); - return GNUNET_JSON_PACK ( - GNUNET_JSON_pack_data_auto ("coin_priv", - &mc->coin_priv), - GNUNET_JSON_pack_data_auto ("h_age_commitment", - &mc->h_age_commitment), - TALER_JSON_pack_denom_sig ("denom_sig", - &mc->sig), - TALER_JSON_pack_denom_pub ("denom_pub", - &mc->pub_key), - TALER_JSON_pack_amount ("melt_amount_with_fee", - &mc->melt_amount_with_fee), - TALER_JSON_pack_amount ("original_value", - &mc->original_value), - TALER_JSON_pack_amount ("melt_fee", - &mc->fee_melt), - GNUNET_JSON_pack_timestamp ("expire_deposit", - mc->expire_deposit), - GNUNET_JSON_pack_array_steal ("transfer_privs", - tprivs)); -} - - -/** - * Deserialize information about a coin we are melting. - * - * @param[out] mc information to deserialize - * @param currency expected currency - * @param in JSON object to read data from - * @return #GNUNET_NO to report errors - */ -static enum GNUNET_GenericReturnValue -deserialize_melted_coin (struct MeltedCoin *mc, - const char *currency, - const json_t *in) -{ - json_t *trans_privs; - struct GNUNET_JSON_Specification spec[] = { - GNUNET_JSON_spec_fixed_auto ("coin_priv", - &mc->coin_priv), - GNUNET_JSON_spec_mark_optional ( - GNUNET_JSON_spec_fixed_auto ("h_age_commitment", - &mc->h_age_commitment)), - TALER_JSON_spec_denom_sig ("denom_sig", - &mc->sig), - TALER_JSON_spec_denom_pub ("denom_pub", - &mc->pub_key), - TALER_JSON_spec_amount ("melt_amount_with_fee", - currency, - &mc->melt_amount_with_fee), - TALER_JSON_spec_amount ("original_value", - currency, - &mc->original_value), - TALER_JSON_spec_amount ("melt_fee", - currency, - &mc->fee_melt), - GNUNET_JSON_spec_timestamp ("expire_deposit", - &mc->expire_deposit), - GNUNET_JSON_spec_json ("transfer_privs", - &trans_privs), - GNUNET_JSON_spec_end () - }; - - if (GNUNET_OK != - GNUNET_JSON_parse (in, - spec, - NULL, NULL)) - { - GNUNET_break_op (0); - return GNUNET_NO; - } - if (TALER_CNC_KAPPA != json_array_size (trans_privs)) - { - GNUNET_JSON_parse_free (spec); - GNUNET_break_op (0); - return GNUNET_NO; - } - for (unsigned int i = 0; itransfer_priv[i]), - GNUNET_JSON_spec_end () - }; - - if (GNUNET_OK != - GNUNET_JSON_parse (json_array_get (trans_privs, - i), - spec, - NULL, NULL)) - { - GNUNET_break_op (0); - GNUNET_JSON_parse_free (spec); - return GNUNET_NO; - } - } - json_decref (trans_privs); - return GNUNET_OK; -} - - -/** - * Serialize melt data. - * - * @param md data to serialize - * @return serialized melt data - */ -static json_t * -serialize_melt_data (const struct MeltData *md) -{ - json_t *fresh_coins; - - fresh_coins = json_array (); - GNUNET_assert (NULL != fresh_coins); - for (int i = 0; inum_fresh_coins; i++) - { - json_t *planchet_secrets; - - planchet_secrets = json_array (); - GNUNET_assert (NULL != planchet_secrets); - for (unsigned int j = 0; jfresh_coins[j][i])); - GNUNET_assert (0 == - json_array_append_new (planchet_secrets, - ps)); - } - GNUNET_assert (0 == - json_array_append_new ( - fresh_coins, - GNUNET_JSON_PACK ( - TALER_JSON_pack_denom_pub ("denom_pub", - &md->fresh_pks[i]), - GNUNET_JSON_pack_array_steal ("planchet_secrets", - planchet_secrets))) - ); - } - return GNUNET_JSON_PACK ( - GNUNET_JSON_pack_array_steal ("fresh_coins", - fresh_coins), - GNUNET_JSON_pack_object_steal ("melted_coin", - serialize_melted_coin (&md->melted_coin)), - GNUNET_JSON_pack_data_auto ("rc", - &md->rc)); -} - - -struct MeltData * -TALER_EXCHANGE_deserialize_melt_data_ (const json_t *melt_data, - const char *currency) -{ - struct MeltData *md = GNUNET_new (struct MeltData); - json_t *fresh_coins; - json_t *melted_coin; - struct GNUNET_JSON_Specification spec[] = { - GNUNET_JSON_spec_fixed_auto ("rc", - &md->rc), - GNUNET_JSON_spec_json ("melted_coin", - &melted_coin), - GNUNET_JSON_spec_json ("fresh_coins", - &fresh_coins), - GNUNET_JSON_spec_end () - }; - bool ok; - - if (GNUNET_OK != - GNUNET_JSON_parse (melt_data, - spec, - NULL, NULL)) - { - GNUNET_break (0); - GNUNET_JSON_parse_free (spec); - GNUNET_free (md); - return NULL; - } - if (! (json_is_array (fresh_coins) && - json_is_object (melted_coin)) ) - { - GNUNET_break (0); - GNUNET_JSON_parse_free (spec); - return NULL; - } - if (GNUNET_OK != - deserialize_melted_coin (&md->melted_coin, - currency, - melted_coin)) - { - GNUNET_break (0); - GNUNET_JSON_parse_free (spec); - return NULL; - } - md->num_fresh_coins = json_array_size (fresh_coins); - md->fresh_pks = GNUNET_new_array (md->num_fresh_coins, - struct TALER_DenominationPublicKey); - for (unsigned int i = 0; ifresh_coins[i] = GNUNET_new_array (md->num_fresh_coins, - struct TALER_PlanchetSecretsP); - ok = true; - for (unsigned int i = 0; inum_fresh_coins; i++) - { - const json_t *ji = json_array_get (fresh_coins, - i); - json_t *planchet_secrets; - struct GNUNET_JSON_Specification ispec[] = { - GNUNET_JSON_spec_json ("planchet_secrets", - &planchet_secrets), - TALER_JSON_spec_denom_pub ("denom_pub", - &md->fresh_pks[i]), - GNUNET_JSON_spec_end () - }; - - if (GNUNET_OK != - GNUNET_JSON_parse (ji, - ispec, - NULL, NULL)) - { - GNUNET_break (0); - ok = false; - break; - } - if ( (! json_is_array (planchet_secrets)) || - (TALER_CNC_KAPPA != json_array_size (planchet_secrets)) ) - { - GNUNET_break (0); - ok = false; - GNUNET_JSON_parse_free (ispec); - break; - } - for (unsigned int j = 0; jfresh_coins[j][i]), - GNUNET_JSON_spec_end () - }; - - if (GNUNET_OK != - GNUNET_JSON_parse (json_array_get (planchet_secrets, - j), - jspec, - NULL, NULL)) - { - GNUNET_break (0); - ok = false; - break; - } - } - json_decref (planchet_secrets); - if (! ok) - break; - } - - GNUNET_JSON_parse_free (spec); - if (! ok) - { - TALER_EXCHANGE_free_melt_data_ (md); - GNUNET_free (md); - return NULL; - } - return md; -} - - -json_t * -TALER_EXCHANGE_refresh_prepare ( - const struct TALER_CoinSpendPrivateKeyP *melt_priv, - const struct TALER_Amount *melt_amount, - const struct TALER_DenominationSignature *melt_sig, - const struct TALER_EXCHANGE_DenomPublicKey *melt_pk, - const struct TALER_AgeCommitment *age_commitment, - unsigned int fresh_pks_len, - const struct TALER_EXCHANGE_DenomPublicKey *fresh_pks) -{ - struct MeltData md; - json_t *ret; struct TALER_Amount total; struct TALER_AgeCommitmentHash ach = {0}; struct TALER_CoinSpendPublicKeyP coin_pub; - struct TALER_TransferSecretP trans_sec[TALER_CNC_KAPPA]; - struct TALER_RefreshCommitmentEntry rce[TALER_CNC_KAPPA]; + struct TALER_CsNonce nonces[rd->fresh_pks_len]; - GNUNET_CRYPTO_eddsa_key_get_public (&melt_priv->eddsa_priv, + GNUNET_CRYPTO_eddsa_key_get_public (&rd->melt_priv.eddsa_priv, &coin_pub.eddsa_pub); /* build up melt data structure */ - memset (&md, + memset (md, 0, - sizeof (md)); - md.num_fresh_coins = fresh_pks_len; - md.melted_coin.coin_priv = *melt_priv; - md.melted_coin.melt_amount_with_fee = *melt_amount; - md.melted_coin.fee_melt = melt_pk->fee_refresh; - md.melted_coin.original_value = melt_pk->value; - md.melted_coin.expire_deposit - = melt_pk->expire_deposit; - md.melted_coin.h_age_commitment = ach; - TALER_age_commitment_hash (age_commitment, - &md.melted_coin.h_age_commitment); - + sizeof (*md)); + md->num_fresh_coins = rd->fresh_pks_len; + md->melted_coin.coin_priv = rd->melt_priv; + md->melted_coin.melt_amount_with_fee = rd->melt_amount; + md->melted_coin.fee_melt = rd->melt_pk.fee_refresh; + md->melted_coin.original_value = rd->melt_pk.value; + md->melted_coin.expire_deposit = rd->melt_pk.expire_deposit; GNUNET_assert (GNUNET_OK == - TALER_amount_set_zero (melt_amount->currency, + TALER_amount_set_zero (rd->melt_amount.currency, &total)); - TALER_denom_pub_deep_copy (&md.melted_coin.pub_key, - &melt_pk->key); - TALER_denom_sig_deep_copy (&md.melted_coin.sig, - melt_sig); - md.fresh_pks = GNUNET_new_array (fresh_pks_len, - struct TALER_DenominationPublicKey); - - for (unsigned int i = 0; imelted_coin.pub_key, + &rd->melt_pk.key); + TALER_denom_sig_deep_copy (&md->melted_coin.sig, + &rd->melt_sig); + md->fcds = GNUNET_new_array (md->num_fresh_coins, + struct FreshCoinData); + for (unsigned int j = 0; jfresh_pks_len; j++) { - TALER_denom_pub_deep_copy (&md.fresh_pks[i], - &fresh_pks[i].key); + struct FreshCoinData *fcd = &md->fcds[j]; + + if (alg_values[j].cipher != rd->fresh_pks[j].key.cipher) + { + GNUNET_break (0); + TALER_EXCHANGE_free_melt_data_ (md); + return GNUNET_SYSERR; + } + if (TALER_DENOMINATION_CS == alg_values[j].cipher) + { + TALER_cs_refresh_nonce_derive ( + rms, + j, + &nonces[j]); + } + TALER_denom_pub_deep_copy (&fcd->fresh_pk, + &rd->fresh_pks[j].key); if ( (0 > TALER_amount_add (&total, &total, - &fresh_pks[i].value)) || + &rd->fresh_pks[j].value)) || (0 > TALER_amount_add (&total, &total, - &fresh_pks[i].fee_withdraw)) ) + &rd->fresh_pks[j].fee_withdraw)) ) { GNUNET_break (0); - TALER_EXCHANGE_free_melt_data_ (&md); - return NULL; + TALER_EXCHANGE_free_melt_data_ (md); + return GNUNET_SYSERR; } } /* verify that melt_amount is above total cost */ if (1 == TALER_amount_cmp (&total, - melt_amount) ) + &rd->melt_amount) ) { /* Eh, this operation is more expensive than the @a melt_amount. This is not OK. */ GNUNET_break (0); - TALER_EXCHANGE_free_melt_data_ (&md); - return NULL; + TALER_EXCHANGE_free_melt_data_ (md); + return GNUNET_SYSERR; } /* build up coins */ for (unsigned int i = 0; itransfer_priv[i]); GNUNET_CRYPTO_ecdhe_key_get_public ( - &md.melted_coin.transfer_priv[i].ecdhe_priv, - &rce[i].transfer_pub.ecdhe_pub); - TALER_link_derive_transfer_secret (melt_priv, - &md.melted_coin.transfer_priv[i], - &trans_sec[i]); - - md.fresh_coins[i] = GNUNET_new_array (fresh_pks_len, - struct TALER_PlanchetSecretsP); - - rce[i].new_coins = GNUNET_new_array (fresh_pks_len, - struct TALER_RefreshCoinData); - - md.fresh_ach[i] = GNUNET_new_array (fresh_pks_len, - struct TALER_AgeCommitmentHash); - - for (unsigned int j = 0; jtransfer_priv[i].ecdhe_priv, + &md->transfer_pub[i].ecdhe_pub); + TALER_link_derive_transfer_secret (&rd->melt_priv, + &md->transfer_priv[i], + &trans_sec); + md->rcd[i] = GNUNET_new_array (rd->fresh_pks_len, + struct TALER_RefreshCoinData); + for (unsigned int j = 0; jfresh_pks_len; j++) { - struct TALER_PlanchetSecretsP *fc = &md.fresh_coins[i][j]; - struct TALER_RefreshCoinData *rcd = &rce[i].new_coins[j]; - struct TALER_AgeCommitmentHash *ach = &md.fresh_ach[i][j]; + struct FreshCoinData *fcd = &md->fcds[j]; + struct TALER_CoinSpendPrivateKeyP *coin_priv = &fcd->coin_priv; + struct TALER_PlanchetMasterSecretP *ps = &fcd->ps[i]; + struct TALER_RefreshCoinData *rcd = &md->rcd[i][j]; + union TALER_DenominationBlindingKeyP *bks = &fcd->bks[i]; struct TALER_PlanchetDetail pd; struct TALER_CoinPubHash c_hash; - - /* Handle age commitment, if present */ - if (NULL == age_commitment) - { - memset (ach, 0, sizeof(struct TALER_AgeCommitmentHash)); - ach = NULL; - } - else - { - struct TALER_AgeCommitment new_ac; - uint32_t seed; - - /* we use the first 4 bytes of the trans_sec to generate a new age - * commitment */ - seed = *(uint32_t *) trans_sec[i].key.bits; - - if (GNUNET_OK != TALER_age_commitment_derive ( - age_commitment, - seed, - &new_ac)) - { - GNUNET_break_op (0); - TALER_EXCHANGE_free_melt_data_ (&md); - return NULL; - } - - TALER_age_commitment_hash ( - &new_ac, - &md.fresh_ach[i][j]); - } - - TALER_planchet_setup_refresh (&trans_sec[i], - j, - fc); + TALER_transfer_secret_to_planchet_secret (&trans_sec, + j, + ps); + TALER_planchet_setup_coin_priv (ps, + &alg_values[j], + coin_priv); + TALER_planchet_blinding_secret_create (ps, + &alg_values[j], + bks); + if (TALER_DENOMINATION_CS == alg_values[j].cipher) + pd.blinded_planchet.details.cs_blinded_planchet.nonce = nonces[j]; if (GNUNET_OK != - TALER_planchet_prepare (&md.fresh_pks[j], - fc, + TALER_planchet_prepare (&fcd->fresh_pk, + &alg_values[j], + bks, + coin_priv, ach, &c_hash, &pd)) { GNUNET_break_op (0); - TALER_EXCHANGE_free_melt_data_ (&md); - return NULL; + TALER_EXCHANGE_free_melt_data_ (md); + return GNUNET_SYSERR; } - rcd->dk = &md.fresh_pks[j]; - rcd->coin_ev = pd.coin_ev; - rcd->coin_ev_size = pd.coin_ev_size; + rcd->blinded_planchet = pd.blinded_planchet; + rcd->dk = &fcd->fresh_pk; } } - /* Compute refresh commitment */ - TALER_refresh_get_commitment (&md.rc, - TALER_CNC_KAPPA, - fresh_pks_len, - rce, - &coin_pub, - melt_amount); - - /* finally, serialize everything */ - ret = serialize_melt_data (&md); - for (unsigned int i = 0; i < TALER_CNC_KAPPA; i++) + /* Finally, compute refresh commitment */ { - for (unsigned int j = 0; j < fresh_pks_len; j++) - GNUNET_free (rce[i].new_coins[j].coin_ev); - GNUNET_free (rce[i].new_coins); - } + struct TALER_RefreshCommitmentEntry rce[TALER_CNC_KAPPA]; - TALER_EXCHANGE_free_melt_data_ (&md); - return ret; + for (unsigned int i = 0; itransfer_pub[i]; + rce[i].new_coins = md->rcd[i]; + } + TALER_refresh_get_commitment (&md->rc, + TALER_CNC_KAPPA, + rd->fresh_pks_len, + rce, + &coin_pub, + &rd->melt_amount); + } + return GNUNET_OK; } diff --git a/src/lib/exchange_api_refresh_common.h b/src/lib/exchange_api_refresh_common.h index 9a08a393f..b6926b51f 100644 --- a/src/lib/exchange_api_refresh_common.h +++ b/src/lib/exchange_api_refresh_common.h @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2015-2020 Taler Systems SA + Copyright (C) 2015-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -58,11 +58,6 @@ struct MeltedCoin */ struct TALER_AgeCommitmentHash h_age_commitment; - /** - * Transfer private keys for each cut-and-choose dimension. - */ - struct TALER_TransferPrivateKeyP transfer_priv[TALER_CNC_KAPPA]; - /** * Timestamp indicating when coins of this denomination become invalid. */ @@ -81,6 +76,44 @@ struct MeltedCoin }; +/** + * Data we keep for each fresh coin created in the + * melt process. + */ +struct FreshCoinData +{ + /** + * Denomination public key of the coin. + */ + struct TALER_DenominationPublicKey fresh_pk; + + /** + * Array of planchet secrets for the coins, depending + * on the cut-and-choose. + */ + struct TALER_PlanchetMasterSecretP ps[TALER_CNC_KAPPA]; + + /** + * Private key of the coin. + */ + struct TALER_CoinSpendPrivateKeyP coin_priv; + + /** + * Arrays age commitments to be created, one for each cut-and-choose + * dimension. The entries in each list might be NULL and indicate no age + * commitment/restriction on the particular coin. + */ + struct TALER_AgeCommitment *age_commitment[TALER_CNC_KAPPA]; + + /** + * Blinding key secrets for the coins, depending on the + * cut-and-choose. + */ + union TALER_DenominationBlindingKeyP bks[TALER_CNC_KAPPA]; + +}; + + /** * Melt data in non-serialized format for convenient processing. */ @@ -92,55 +125,72 @@ struct MeltData */ struct TALER_RefreshCommitmentP rc; - /** - * Number of coins we are creating - */ - uint16_t num_fresh_coins; - /** * Information about the melted coin. */ struct MeltedCoin melted_coin; /** - * Array of @e num_fresh_coins denomination keys for the coins to be - * freshly exchangeed. + * Array of length @e num_fresh_coins with information + * about each fresh coin. */ - struct TALER_DenominationPublicKey *fresh_pks; + struct FreshCoinData *fcds; /** - * Arrays of @e num_fresh_coins with information about the fresh - * coins to be created, for each cut-and-choose dimension. + * Transfer secrets, one per cut and choose. */ - struct TALER_PlanchetSecretsP *fresh_coins[TALER_CNC_KAPPA]; + struct TALER_TransferSecretP trans_sec[TALER_CNC_KAPPA]; /** - * Arrays of @e num_fresh_coins with information about the hashes of age - * commitments coins to be created, for each cut-and-choose dimension. The - * entries in each list might be NULL and indicate no age - * commitment/restriction on the particular coin. + * Transfer private keys for each cut-and-choose dimension. */ - struct TALER_AgeCommitmentHash *fresh_ach[TALER_CNC_KAPPA]; + struct TALER_TransferPrivateKeyP transfer_priv[TALER_CNC_KAPPA]; + + /** + * Transfer public key of this commitment. + */ + struct TALER_TransferPublicKeyP transfer_pub[TALER_CNC_KAPPA]; + + /** + * Transfer secrets, one per cut and choose. + */ + struct TALER_RefreshCommitmentEntry rce[TALER_CNC_KAPPA]; + + /** + * Blinded planchets and denominations of the fresh coins, depending on the cut-and-choose. Array of length + * @e num_fresh_coins. + */ + struct TALER_RefreshCoinData *rcd[TALER_CNC_KAPPA]; + + /** + * Number of coins we are creating + */ + uint16_t num_fresh_coins; + }; /** - * Deserialize melt data. + * Compute the melt data from the refresh data and secret. * - * @param data json data to deserialize - * @param currency expected currency for the coins - * @return deserialized melt data, NULL on error + * @param rms secret internals of the refresh-reveal operation + * @param rd refresh data with the characteristics of the operation + * @param alg_values contributions from the exchange into the melt + * @param[out] md where to write the derived melt data */ -struct MeltData * -TALER_EXCHANGE_deserialize_melt_data_ (const json_t *data, - const char *currency); +enum GNUNET_GenericReturnValue +TALER_EXCHANGE_get_melt_data_ ( + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, + const struct TALER_ExchangeWithdrawValues *alg_values, + struct MeltData *md); /** * Free all information associated with a melting session. Note * that we allow the melting session to be only partially initialized, * as we use this function also when freeing melt data that was not - * fully initialized (i.e. due to failures in #TALER_EXCHANGE_deserialize_melt_data_()). + * fully initialized. * * @param[in] md melting data to release, the pointer itself is NOT * freed (as it is typically not allocated by itself) diff --git a/src/lib/exchange_api_refreshes_reveal.c b/src/lib/exchange_api_refreshes_reveal.c index 743ea70dd..5714d743b 100644 --- a/src/lib/exchange_api_refreshes_reveal.c +++ b/src/lib/exchange_api_refreshes_reveal.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2015-2021 Taler Systems SA + Copyright (C) 2015-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -60,6 +60,11 @@ struct TALER_EXCHANGE_RefreshesRevealHandle */ struct GNUNET_CURL_Job *job; + /** + * Exchange-contributed values to the operation. + */ + struct TALER_ExchangeWithdrawValues *alg_values; + /** * Function to call with the result. */ @@ -73,7 +78,7 @@ struct TALER_EXCHANGE_RefreshesRevealHandle /** * Actual information about the melt operation. */ - struct MeltData *md; + struct MeltData md; /** * The index selected by the exchange in cut-and-choose to not be revealed. @@ -84,24 +89,23 @@ struct TALER_EXCHANGE_RefreshesRevealHandle /** - * We got a 200 OK response for the /refreshes/$RCH/reveal operation. - * Extract the coin signatures and return them to the caller. - * The signatures we get from the exchange is for the blinded value. - * Thus, we first must unblind them and then should verify their - * validity. + * We got a 200 OK response for the /refreshes/$RCH/reveal operation. Extract + * the coin signatures and return them to the caller. The signatures we get + * from the exchange is for the blinded value. Thus, we first must unblind + * them and then should verify their validity. * * If everything checks out, we return the unblinded signatures * to the application via the callback. * * @param rrh operation handle * @param json reply from the exchange - * @param[out] sigs array of length `num_fresh_coins`, initialized to contain RSA signatures + * @param[out] rcis array of length `num_fresh_coins`, initialized to contain the coin data * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors */ static enum GNUNET_GenericReturnValue refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, const json_t *json, - struct TALER_DenominationSignature *sigs) + struct TALER_EXCHANGE_RevealedCoinInfo *rcis) { json_t *jsona; struct GNUNET_JSON_Specification outer_spec[] = { @@ -125,17 +129,19 @@ refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, GNUNET_JSON_parse_free (outer_spec); return GNUNET_SYSERR; } - if (rrh->md->num_fresh_coins != json_array_size (jsona)) + if (rrh->md.num_fresh_coins != json_array_size (jsona)) { /* Number of coins generated does not match our expectation */ GNUNET_break_op (0); GNUNET_JSON_parse_free (outer_spec); return GNUNET_SYSERR; } - for (unsigned int i = 0; imd->num_fresh_coins; i++) + for (unsigned int i = 0; imd.num_fresh_coins; i++) { - const struct TALER_PlanchetSecretsP *fc; - struct TALER_DenominationPublicKey *pk; + struct TALER_EXCHANGE_RevealedCoinInfo *rci = + &rcis[i]; + const struct FreshCoinData *fcd = &rrh->md.fcds[i]; + const struct TALER_DenominationPublicKey *pk; struct TALER_AgeCommitmentHash *ach = NULL; json_t *jsonai; struct TALER_BlindedDenominationSignature blind_sig; @@ -147,9 +153,11 @@ refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, GNUNET_JSON_spec_end () }; struct TALER_FreshCoin coin; + union TALER_DenominationBlindingKeyP bks; - fc = &rrh->md->fresh_coins[rrh->noreveal_index][i]; - pk = &rrh->md->fresh_pks[i]; + rci->ps = fcd->ps[rrh->noreveal_index]; + rci->bks = fcd->bks[rrh->noreveal_index]; + pk = &fcd->fresh_pk; jsonai = json_array_get (jsona, i); GNUNET_assert (NULL != jsonai); @@ -169,9 +177,15 @@ refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, return GNUNET_SYSERR; } + TALER_planchet_setup_coin_priv (&rci->ps, + &rrh->alg_values[i], + &rci->coin_priv); + TALER_planchet_blinding_secret_create (&rci->ps, + &rrh->alg_values[i], + &bks); /* needed to verify the signature, and we didn't store it earlier, hence recomputing it here... */ - GNUNET_CRYPTO_eddsa_key_get_public (&fc->coin_priv.eddsa_priv, + GNUNET_CRYPTO_eddsa_key_get_public (&rci->coin_priv.eddsa_priv, &coin_pub.eddsa_pub); TALER_coin_pub_hash (&coin_pub, ach, @@ -179,9 +193,11 @@ refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, if (GNUNET_OK != TALER_planchet_to_coin (pk, &blind_sig, - fc, + &bks, + &rci->coin_priv, ach, &coin_hash, + &rrh->alg_values[i], &coin)) { GNUNET_break_op (0); @@ -190,7 +206,7 @@ refresh_reveal_ok (struct TALER_EXCHANGE_RefreshesRevealHandle *rrh, return GNUNET_SYSERR; } GNUNET_JSON_parse_free (spec); - sigs[i] = coin.sig; + rci->sig = coin.sig; } GNUNET_JSON_parse_free (outer_spec); return GNUNET_OK; @@ -212,88 +228,86 @@ handle_refresh_reveal_finished (void *cls, { struct TALER_EXCHANGE_RefreshesRevealHandle *rrh = cls; const json_t *j = response; - struct TALER_EXCHANGE_HttpResponse hr = { - .reply = j, - .http_status = (unsigned int) response_code + struct TALER_EXCHANGE_RevealResult rr = { + .hr.reply = j, + .hr.http_status = (unsigned int) response_code }; rrh->job = NULL; switch (response_code) { case 0: - hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; + rr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE; break; case MHD_HTTP_OK: { - struct TALER_DenominationSignature sigs[rrh->md->num_fresh_coins]; - int ret; + struct TALER_EXCHANGE_RevealedCoinInfo rcis[rrh->md.num_fresh_coins]; + enum GNUNET_GenericReturnValue ret; - memset (sigs, + memset (rcis, 0, - sizeof (sigs)); + sizeof (rcis)); ret = refresh_reveal_ok (rrh, j, - sigs); + rcis); if (GNUNET_OK != ret) { - hr.http_status = 0; - hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; + rr.hr.http_status = 0; + rr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED; + break; } else { + GNUNET_assert (rrh->noreveal_index < TALER_CNC_KAPPA); + rr.details.success.num_coins = rrh->md.num_fresh_coins; + rr.details.success.coins = rcis; rrh->reveal_cb (rrh->reveal_cb_cls, - &hr, - rrh->md->num_fresh_coins, - rrh->md->fresh_coins[rrh->noreveal_index], - sigs); + &rr); rrh->reveal_cb = NULL; } - for (unsigned int i = 0; imd->num_fresh_coins; i++) - TALER_denom_sig_free (&sigs[i]); + for (unsigned int i = 0; imd.num_fresh_coins; i++) + TALER_denom_sig_free (&rcis[i].sig); TALER_EXCHANGE_refreshes_reveal_cancel (rrh); return; } case MHD_HTTP_BAD_REQUEST: /* This should never happen, either us or the exchange is buggy (or API version conflict); just pass JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + rr.hr.ec = TALER_JSON_get_error_code (j); + rr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_CONFLICT: /* Nothing really to verify, exchange says our reveal is inconsistent with our commitment, so either side is buggy; we should pass the JSON reply to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + rr.hr.ec = TALER_JSON_get_error_code (j); + rr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_GONE: /* Server claims key expired or has been revoked */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + rr.hr.ec = TALER_JSON_get_error_code (j); + rr.hr.hint = TALER_JSON_get_error_hint (j); break; case MHD_HTTP_INTERNAL_SERVER_ERROR: /* Server had an internal issue; we should retry, but this API leaves this to the application */ - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + rr.hr.ec = TALER_JSON_get_error_code (j); + rr.hr.hint = TALER_JSON_get_error_hint (j); break; default: /* unexpected response code */ GNUNET_break_op (0); - hr.ec = TALER_JSON_get_error_code (j); - hr.hint = TALER_JSON_get_error_hint (j); + rr.hr.ec = TALER_JSON_get_error_code (j); + rr.hr.hint = TALER_JSON_get_error_hint (j); GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected response code %u/%d for exchange refreshes reveal\n", (unsigned int) response_code, - (int) hr.ec); + (int) rr.hr.ec); break; } if (NULL != rrh->reveal_cb) rrh->reveal_cb (rrh->reveal_cb_cls, - &hr, - 0, - NULL, - NULL); + &rr); TALER_EXCHANGE_refreshes_reveal_cancel (rrh); } @@ -301,7 +315,10 @@ handle_refresh_reveal_finished (void *cls, struct TALER_EXCHANGE_RefreshesRevealHandle * TALER_EXCHANGE_refreshes_reveal ( struct TALER_EXCHANGE_Handle *exchange, - const json_t *refresh_data, + const struct TALER_RefreshMasterSecretP *rms, + const struct TALER_EXCHANGE_RefreshData *rd, + unsigned int num_coins, + const struct TALER_ExchangeWithdrawValues *alg_values, uint32_t noreveal_index, TALER_EXCHANGE_RefreshesRevealCallback reveal_cb, void *reveal_cb_cls) @@ -314,10 +331,10 @@ TALER_EXCHANGE_refreshes_reveal ( json_t *link_sigs; CURL *eh; struct GNUNET_CURL_Context *ctx; - struct MeltData *md; - struct TALER_TransferPublicKeyP transfer_pub; + struct MeltData md; char arg_str[sizeof (struct TALER_RefreshCommitmentP) * 2 + 32]; + GNUNET_assert (num_coins == rd->fresh_pks_len); if (noreveal_index >= TALER_CNC_KAPPA) { /* We check this here, as it would be really bad to below just @@ -333,68 +350,56 @@ TALER_EXCHANGE_refreshes_reveal ( GNUNET_break (0); return NULL; } - md = TALER_EXCHANGE_deserialize_melt_data_ (refresh_data, - exchange->key_data.currency); - if (NULL == md) + if (GNUNET_OK != + TALER_EXCHANGE_get_melt_data_ (rms, + rd, + alg_values, + &md)) { GNUNET_break (0); return NULL; } - /* now transfer_pub */ - GNUNET_CRYPTO_ecdhe_key_get_public ( - &md->melted_coin.transfer_priv[noreveal_index].ecdhe_priv, - &transfer_pub.ecdhe_pub); - /* now new_denoms */ GNUNET_assert (NULL != (new_denoms_h = json_array ())); GNUNET_assert (NULL != (coin_evs = json_array ())); GNUNET_assert (NULL != (link_sigs = json_array ())); - for (unsigned int i = 0; inum_fresh_coins; i++) + for (unsigned int i = 0; ifresh_pks[i], + TALER_denom_pub_hash (&md.fcds[i].fresh_pk, &denom_hash); GNUNET_assert (0 == json_array_append_new (new_denoms_h, GNUNET_JSON_from_data_auto ( &denom_hash))); - - if (GNUNET_OK != - TALER_planchet_prepare (&md->fresh_pks[i], - &md->fresh_coins[noreveal_index][i], - NULL, /* FIXME-oec */ - &c_hash, - &pd)) - { - /* This should have been noticed during the preparation stage. */ - GNUNET_break (0); - json_decref (new_denoms_h); - json_decref (coin_evs); - return NULL; - } GNUNET_assert (0 == - json_array_append_new (coin_evs, - GNUNET_JSON_from_data (pd.coin_ev, - pd.coin_ev_size))); + json_array_append_new ( + coin_evs, + GNUNET_JSON_PACK ( + TALER_JSON_pack_blinded_planchet ( + NULL, + &rcd->blinded_planchet)))); { struct TALER_CoinSpendSignatureP link_sig; + struct TALER_BlindedCoinHash bch; - TALER_wallet_link_sign (&denom_hash, - &transfer_pub, - pd.coin_ev, - pd.coin_ev_size, - &md->melted_coin.coin_priv, - &link_sig); + TALER_coin_ev_hash (&rcd->blinded_planchet, + &denom_hash, + &bch); + TALER_wallet_link_sign ( + &denom_hash, + &md.transfer_pub[noreveal_index], + &bch, + &md.melted_coin.coin_priv, + &link_sig); GNUNET_assert (0 == json_array_append_new ( link_sigs, GNUNET_JSON_from_data_auto (&link_sig))); } - GNUNET_free (pd.coin_ev); } /* build array of transfer private keys */ @@ -403,20 +408,19 @@ TALER_EXCHANGE_refreshes_reveal ( { if (j == noreveal_index) { - /* This is crucial: exclude the transfer key for the - noreval index! */ + /* This is crucial: exclude the transfer key for the noreval index! */ continue; } GNUNET_assert (0 == json_array_append_new (transfer_privs, GNUNET_JSON_from_data_auto ( - &md->melted_coin.transfer_priv[j]))); + &md.transfer_priv[j]))); } /* build main JSON request */ reveal_obj = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("transfer_pub", - &transfer_pub), + &md.transfer_pub[noreveal_index]), GNUNET_JSON_pack_array_steal ("transfer_privs", transfer_privs), GNUNET_JSON_pack_array_steal ("link_sigs", @@ -429,9 +433,8 @@ TALER_EXCHANGE_refreshes_reveal ( char pub_str[sizeof (struct TALER_RefreshCommitmentP) * 2]; char *end; - end = GNUNET_STRINGS_data_to_string (&md->rc, - sizeof (struct - TALER_RefreshCommitmentP), + end = GNUNET_STRINGS_data_to_string (&md.rc, + sizeof (md.rc), pub_str, sizeof (pub_str)); *end = '\0'; @@ -447,11 +450,17 @@ TALER_EXCHANGE_refreshes_reveal ( rrh->reveal_cb = reveal_cb; rrh->reveal_cb_cls = reveal_cb_cls; rrh->md = md; + rrh->alg_values = GNUNET_memdup (alg_values, + md.num_fresh_coins + * sizeof (struct + TALER_ExchangeWithdrawValues)); rrh->url = TEAH_path_to_url (rrh->exchange, arg_str); if (NULL == rrh->url) { json_decref (reveal_obj); + TALER_EXCHANGE_free_melt_data_ (&md); + GNUNET_free (rrh->alg_values); GNUNET_free (rrh); return NULL; } @@ -466,6 +475,8 @@ TALER_EXCHANGE_refreshes_reveal ( if (NULL != eh) curl_easy_cleanup (eh); json_decref (reveal_obj); + TALER_EXCHANGE_free_melt_data_ (&md); + GNUNET_free (rrh->alg_values); GNUNET_free (rrh->url); GNUNET_free (rrh); return NULL; @@ -490,10 +501,10 @@ TALER_EXCHANGE_refreshes_reveal_cancel ( GNUNET_CURL_job_cancel (rrh->job); rrh->job = NULL; } + GNUNET_free (rrh->alg_values); GNUNET_free (rrh->url); TALER_curl_easy_post_finished (&rrh->ctx); - TALER_EXCHANGE_free_melt_data_ (rrh->md); /* does not free 'md' itself */ - GNUNET_free (rrh->md); + TALER_EXCHANGE_free_melt_data_ (&rrh->md); GNUNET_free (rrh); } diff --git a/src/lib/exchange_api_withdraw.c b/src/lib/exchange_api_withdraw.c index 92b2a567f..8bd9894ca 100644 --- a/src/lib/exchange_api_withdraw.c +++ b/src/lib/exchange_api_withdraw.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -59,9 +59,34 @@ struct TALER_EXCHANGE_WithdrawHandle void *cb_cls; /** - * Secrets of the planchet. + * Reserve private key. */ - struct TALER_PlanchetSecretsP ps; + const struct TALER_ReservePrivateKeyP *reserve_priv; + + /** + * Seed of the planchet. + */ + struct TALER_PlanchetMasterSecretP ps; + + /** + * blinding secret + */ + union TALER_DenominationBlindingKeyP bks; + + /** + * Private key of the coin we are withdrawing. + */ + struct TALER_CoinSpendPrivateKeyP priv; + + /** + * Details of the planchet. + */ + struct TALER_PlanchetDetail pd; + + /** + * Values of the @cipher selected + */ + struct TALER_ExchangeWithdrawValues alg_values; /** * Hash of the age commitment for this coin, if applicable. Maybe NULL @@ -78,6 +103,11 @@ struct TALER_EXCHANGE_WithdrawHandle */ struct TALER_CoinPubHash c_hash; + /** + * Handler for the CS R request (only used for TALER_DENOMINATION_CS denominations) + */ + struct TALER_EXCHANGE_CsRHandle *csrh; + }; @@ -110,16 +140,21 @@ handle_reserve_withdraw_finished ( if (GNUNET_OK != TALER_planchet_to_coin (&wh->pk.key, blind_sig, - &wh->ps, + &wh->bks, + &wh->priv, wh->ach, &wh->c_hash, + &wh->alg_values, &fc)) { wr.hr.http_status = 0; wr.hr.ec = TALER_EC_EXCHANGE_WITHDRAW_UNBLIND_FAILURE; break; } + wr.details.success.coin_priv = wh->priv; + wr.details.success.bks = wh->bks; wr.details.success.sig = fc.sig; + wr.details.success.exchange_vals = wh->alg_values; break; } case MHD_HTTP_ACCEPTED: @@ -154,35 +189,76 @@ handle_reserve_withdraw_finished ( /** - * Withdraw a coin from the exchange using a /reserve/withdraw request. Note - * that to ensure that no money is lost in case of hardware failures, - * the caller must have committed (most of) the arguments to disk - * before calling, and be ready to repeat the request with the same - * arguments in case of failures. + * Function called when stage 1 of CS withdraw is finished (request r_pub's) * - * @param exchange the exchange handle; the exchange must be ready to operate - * @param pk kind of coin to create - * @param reserve_priv private key of the reserve to withdraw from - * @param ps secrets of the planchet - * caller must have committed this value to disk before the call (with @a pk) - * @param ach (optional) hash of the age commitment that should be bound to this coin. Maybe NULL. - * @param res_cb the callback to call when the final result for this request is available - * @param res_cb_cls closure for the above callback - * @return handle for the operation on success, NULL on error, i.e. - * if the inputs are invalid (i.e. denomination key not with this exchange). - * In this case, the callback is not called. + * @param cls the `struct TALER_EXCHANGE_WithdrawHandle` + * @param csrr replies from the /csr request */ +static void +withdraw_cs_stage_two_callback (void *cls, + const struct TALER_EXCHANGE_CsRResponse *csrr) +{ + struct TALER_EXCHANGE_WithdrawHandle *wh = cls; + struct TALER_EXCHANGE_WithdrawResponse wr = { + .hr = csrr->hr + }; + + wh->csrh = NULL; + GNUNET_assert (TALER_DENOMINATION_CS == wh->pk.key.cipher); + switch (csrr->hr.http_status) + { + case MHD_HTTP_OK: + if (1 != csrr->details.success.alg_values_len) + { + GNUNET_break (0); + wr.hr.http_status = 0; + break; + } + wh->alg_values = csrr->details.success.alg_values[0]; + TALER_planchet_setup_coin_priv (&wh->ps, + &wh->alg_values, + &wh->priv); + TALER_planchet_blinding_secret_create (&wh->ps, + &wh->alg_values, + &wh->bks); + /* This initializes the 2nd half of the + wh->pd.blinded_planchet! */ + if (GNUNET_OK != + TALER_planchet_prepare (&wh->pk.key, + &wh->alg_values, + &wh->bks, + &wh->priv, + &wh->c_hash, + &wh->pd)) + { + GNUNET_break (0); + GNUNET_free (wh); + } + wh->wh2 = TALER_EXCHANGE_withdraw2 (wh->exchange, + &wh->pd, + wh->reserve_priv, + &handle_reserve_withdraw_finished, + wh); + return; + default: + break; + } + wh->cb (wh->cb_cls, + &wr); + TALER_EXCHANGE_withdraw_cancel (wh); +} + + struct TALER_EXCHANGE_WithdrawHandle * TALER_EXCHANGE_withdraw ( struct TALER_EXCHANGE_Handle *exchange, const struct TALER_EXCHANGE_DenomPublicKey *pk, const struct TALER_ReservePrivateKeyP *reserve_priv, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_PlanchetMasterSecretP *ps, const struct TALER_AgeCommitmentHash *ach, TALER_EXCHANGE_WithdrawCallback res_cb, void *res_cb_cls) { - struct TALER_PlanchetDetail pd; struct TALER_EXCHANGE_WithdrawHandle *wh; bool age_restricted = (0 != pk->key.age_mask.mask); @@ -190,31 +266,69 @@ TALER_EXCHANGE_withdraw ( wh->exchange = exchange; wh->cb = res_cb; wh->cb_cls = res_cb_cls; - wh->pk = *pk; + wh->reserve_priv = reserve_priv; wh->ps = *ps; wh->ach = ach; + wh->pk = *pk; + TALER_denom_pub_deep_copy (&wh->pk.key, + &pk->key); - GNUNET_assert (age_restricted == (NULL != ach)); - - if (GNUNET_OK != - TALER_planchet_prepare (&pk->key, - ps, - ach, - &wh->c_hash, - &pd)) + switch (pk->key.cipher) { + case TALER_DENOMINATION_RSA: + { + wh->alg_values.cipher = TALER_DENOMINATION_RSA; + TALER_planchet_setup_coin_priv (ps, + &wh->alg_values, + &wh->priv); + TALER_planchet_blinding_secret_create (ps, + &wh->alg_values, + &wh->bks); + if (GNUNET_OK != + TALER_planchet_prepare (&pk->key, + &wh->alg_values, + &wh->bks, + &wh->priv, + &wh->ach, + &wh->c_hash, + &wh->pd)) + { + GNUNET_break (0); + GNUNET_free (wh); + return NULL; + } + wh->wh2 = TALER_EXCHANGE_withdraw2 (exchange, + &wh->pd, + wh->reserve_priv, + &handle_reserve_withdraw_finished, + wh); + break; + } + case TALER_DENOMINATION_CS: + { + struct TALER_EXCHANGE_NonceKey nk = { + .pk = pk, + }; + + TALER_cs_withdraw_nonce_derive (ps, + &nk.nonce); + /* Note that we only initialize the first half + of the blinded_planchet here; the other part + will be done after the /csr request! */ + wh->pd.blinded_planchet.cipher = TALER_DENOMINATION_CS; + wh->pd.blinded_planchet.details.cs_blinded_planchet.nonce = nk.nonce; + wh->csrh = TALER_EXCHANGE_csr (exchange, + 1, /* "array" length */ + &nk, + &withdraw_cs_stage_two_callback, + wh); + break; + } + default: GNUNET_break (0); GNUNET_free (wh); return NULL; } - TALER_denom_pub_deep_copy (&wh->pk.key, - &pk->key); - wh->wh2 = TALER_EXCHANGE_withdraw2 (exchange, - &pd, - reserve_priv, - &handle_reserve_withdraw_finished, - wh); - GNUNET_free (pd.coin_ev); return wh; } @@ -222,6 +336,12 @@ TALER_EXCHANGE_withdraw ( void TALER_EXCHANGE_withdraw_cancel (struct TALER_EXCHANGE_WithdrawHandle *wh) { + TALER_blinded_planchet_free (&wh->pd.blinded_planchet); + if (NULL != wh->csrh) + { + TALER_EXCHANGE_csr_cancel (wh->csrh); + wh->csrh = NULL; + } if (NULL != wh->wh2) { TALER_EXCHANGE_withdraw2_cancel (wh->wh2); diff --git a/src/lib/exchange_api_withdraw2.c b/src/lib/exchange_api_withdraw2.c index d50892e5b..c0643b9af 100644 --- a/src/lib/exchange_api_withdraw2.c +++ b/src/lib/exchange_api_withdraw2.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -152,7 +152,8 @@ reserve_withdraw_payment_required ( json_t *history; size_t len; struct GNUNET_JSON_Specification spec[] = { - TALER_JSON_spec_amount_any ("balance", &balance), + TALER_JSON_spec_amount_any ("balance", + &balance), GNUNET_JSON_spec_end () }; @@ -182,9 +183,9 @@ reserve_withdraw_payment_required ( not fit on the stack. Use "GNUNET_malloc_large" as a malicious exchange may theoretically try to crash us by giving a history that does not fit into our memory. */ - rhistory = GNUNET_malloc_large (sizeof (struct - TALER_EXCHANGE_ReserveHistory) - * len); + rhistory = GNUNET_malloc_large ( + sizeof (struct TALER_EXCHANGE_ReserveHistory) + * len); if (NULL == rhistory) { GNUNET_break (0); @@ -379,6 +380,7 @@ TALER_EXCHANGE_withdraw2 ( const struct TALER_EXCHANGE_DenomPublicKey *dk; struct TALER_ReserveSignatureP reserve_sig; char arg_str[sizeof (struct TALER_ReservePublicKeyP) * 2 + 32]; + struct TALER_BlindedCoinHash bch; keys = TALER_EXCHANGE_get_keys (exchange); if (NULL == keys) @@ -427,33 +429,28 @@ TALER_EXCHANGE_withdraw2 ( "/reserves/%s/withdraw", pub_str); } - { - struct TALER_WithdrawRequestPS req = { - .purpose.size = htonl (sizeof (struct TALER_WithdrawRequestPS)), - .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW), - .reserve_pub = wh->reserve_pub, - .h_denomination_pub = pd->denom_pub_hash - }; - TALER_amount_hton (&req.amount_with_fee, - &wh->requested_amount); - TALER_coin_ev_hash (pd->coin_ev, - pd->coin_ev_size, - &req.h_coin_envelope); - GNUNET_CRYPTO_eddsa_sign (&reserve_priv->eddsa_priv, - &req, - &reserve_sig.eddsa_signature); + if (GNUNET_OK != + TALER_coin_ev_hash (&pd->blinded_planchet, + &pd->denom_pub_hash, + &bch)) + { + GNUNET_break (0); + GNUNET_free (wh); + return NULL; } + TALER_wallet_withdraw_sign (&pd->denom_pub_hash, + &wh->requested_amount, + &bch, + reserve_priv, + &reserve_sig); { - json_t *withdraw_obj; - - withdraw_obj = GNUNET_JSON_PACK ( + json_t *withdraw_obj = GNUNET_JSON_PACK ( GNUNET_JSON_pack_data_auto ("denom_pub_hash", &pd->denom_pub_hash), - GNUNET_JSON_pack_data_varsize ("coin_ev", - pd->coin_ev, - pd->coin_ev_size), + TALER_JSON_pack_blinded_planchet ("coin_ev", + &pd->blinded_planchet), GNUNET_JSON_pack_data_auto ("reserve_sig", &reserve_sig)); GNUNET_log (GNUNET_ERROR_TYPE_INFO, diff --git a/src/mhd/mhd_parsing.c b/src/mhd/mhd_parsing.c index 4415c82a8..bae10e724 100644 --- a/src/mhd/mhd_parsing.c +++ b/src/mhd/mhd_parsing.c @@ -27,29 +27,6 @@ #include "taler_mhd_lib.h" -/** - * Process a POST request containing a JSON object. This function - * realizes an MHD POST processor that will (incrementally) process - * JSON data uploaded to the HTTP server. It will store the required - * state in the @a con_cls, which must be cleaned up using - * #TALER_MHD_parse_post_cleanup_callback(). - * - * @param connection the MHD connection - * @param con_cls the closure (points to a `struct Buffer *`) - * @param upload_data the POST data - * @param upload_data_size number of bytes in @a upload_data - * @param json the JSON object for a completed request - * @return - * #GNUNET_YES if json object was parsed or at least - * may be parsed in the future (call again); - * `*json` will be NULL if we need to be called again, - * and non-NULL if we are done. - * #GNUNET_NO is request incomplete or invalid - * (error message was generated) - * #GNUNET_SYSERR on internal error - * (we could not even queue an error message, - * close HTTP session with MHD_NO) - */ enum GNUNET_GenericReturnValue TALER_MHD_parse_post_json (struct MHD_Connection *connection, void **con_cls, @@ -102,13 +79,6 @@ TALER_MHD_parse_post_json (struct MHD_Connection *connection, } -/** - * Function called whenever we are done with a request - * to clean up our state. - * - * @param con_cls value as it was left by - * #TALER_MHD_parse_post_json(), to be cleaned up - */ void TALER_MHD_parse_post_cleanup_callback (void *con_cls) { @@ -116,22 +86,7 @@ TALER_MHD_parse_post_cleanup_callback (void *con_cls) } -/** - * Extract base32crockford encoded data from request. - * - * Queues an error response to the connection if the parameter is - * missing or invalid. - * - * @param connection the MHD connection - * @param param_name the name of the parameter with the key - * @param[out] out_data pointer to store the result - * @param out_size expected size of data - * @return - * #GNUNET_YES if the the argument is present - * #GNUNET_NO if the argument is absent or malformed - * #GNUNET_SYSERR on internal error (error response could not be sent) - */ -int +enum GNUNET_GenericReturnValue TALER_MHD_parse_request_arg_data (struct MHD_Connection *connection, const char *param_name, void *out_data, @@ -166,20 +121,6 @@ TALER_MHD_parse_request_arg_data (struct MHD_Connection *connection, } -/** - * Parse JSON object into components based on the given field - * specification. Generates error response on parse errors. - * - * @param connection the connection to send an error response to - * @param root the JSON node to start the navigation at. - * @param[in,out] spec field specification for the parser - * @return - * #GNUNET_YES if navigation was successful (caller is responsible - * for freeing allocated variable-size data using - * GNUNET_JSON_parse_free() when done) - * #GNUNET_NO if json is malformed, error response was generated - * #GNUNET_SYSERR on internal error - */ enum GNUNET_GenericReturnValue TALER_MHD_parse_json_data (struct MHD_Connection *connection, const json_t *root, @@ -217,24 +158,6 @@ TALER_MHD_parse_json_data (struct MHD_Connection *connection, } -/** - * Parse JSON object that we (the server!) generated into components based on - * the given field specification. The difference to - * #TALER_MHD_parse_json_data() is that this function will fail - * with an HTTP failure of 500 (internal server error) in case - * parsing fails, instead of blaming it on the client with a - * 400 (#MHD_HTTP_BAD_REQUEST). - * - * @param connection the connection to send an error response to - * @param root the JSON node to start the navigation at. - * @param spec field specification for the parser - * @return - * #GNUNET_YES if navigation was successful (caller is responsible - * for freeing allocated variable-size data using - * GNUNET_JSON_parse_free() when done) - * #GNUNET_NO if json is malformed, error response was generated - * #GNUNET_SYSERR on internal error - */ enum GNUNET_GenericReturnValue TALER_MHD_parse_internal_json_data (struct MHD_Connection *connection, const json_t *root, @@ -272,21 +195,6 @@ TALER_MHD_parse_internal_json_data (struct MHD_Connection *connection, } -/** - * Parse JSON array into components based on the given field - * specification. Generates error response on parse errors. - * - * @param connection the connection to send an error response to - * @param root the JSON node to start the navigation at. - * @param[in,out] spec field specification for the parser - * @param ... -1-terminated list of array offsets of type 'int' - * @return - * #GNUNET_YES if navigation was successful (caller is responsible - * for freeing allocated variable-size data using - * GNUNET_JSON_parse_free() when done) - * #GNUNET_NO if json is malformed, error response was generated - * #GNUNET_SYSERR on internal error - */ enum GNUNET_GenericReturnValue TALER_MHD_parse_json_array (struct MHD_Connection *connection, const json_t *root, diff --git a/src/pq/pq_query_helper.c b/src/pq/pq_query_helper.c index 37d7bf5be..efa250125 100644 --- a/src/pq/pq_query_helper.c +++ b/src/pq/pq_query_helper.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014, 2015, 2016, 2021 Taler Systems SA + Copyright (C) 2014, 2015, 2016, 2021, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -194,7 +194,9 @@ qconv_denom_pub (void *cls, denom_pub->details.rsa_public_key, &tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + tlen = sizeof (denom_pub->details.cs_public_key); + break; default: GNUNET_assert (0); } @@ -211,7 +213,11 @@ qconv_denom_pub (void *cls, tlen); GNUNET_free (tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + memcpy (&buf[sizeof (be)], + &denom_pub->details.cs_public_key, + tlen); + break; default: GNUNET_assert (0); } @@ -284,7 +290,9 @@ qconv_denom_sig (void *cls, denom_sig->details.rsa_signature, &tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + tlen = sizeof (denom_sig->details.cs_signature); + break; default: GNUNET_assert (0); } @@ -301,7 +309,11 @@ qconv_denom_sig (void *cls, tlen); GNUNET_free (tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + memcpy (&buf[sizeof (be)], + &denom_sig->details.cs_signature, + tlen); + break; default: GNUNET_assert (0); } @@ -374,7 +386,9 @@ qconv_blinded_denom_sig (void *cls, denom_sig->details.blinded_rsa_signature, &tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + tlen = sizeof (denom_sig->details.blinded_cs_answer); + break; default: GNUNET_assert (0); } @@ -391,7 +405,11 @@ qconv_blinded_denom_sig (void *cls, tlen); GNUNET_free (tbuf); break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + memcpy (&buf[sizeof (be)], + &denom_sig->details.blinded_cs_answer, + tlen); + break; default: GNUNET_assert (0); } @@ -418,6 +436,185 @@ TALER_PQ_query_param_blinded_denom_sig ( } +/** + * Function called to convert input argument into SQL parameters. + * + * @param cls closure + * @param data pointer to input argument + * @param data_len number of bytes in @a data (if applicable) + * @param[out] param_values SQL data to set + * @param[out] param_lengths SQL length data to set + * @param[out] param_formats SQL format data to set + * @param param_length number of entries available in the @a param_values, @a param_lengths and @a param_formats arrays + * @param[out] scratch buffer for dynamic allocations (to be done via #GNUNET_malloc() + * @param scratch_length number of entries left in @a scratch + * @return -1 on error, number of offsets used in @a scratch otherwise + */ +static int +qconv_blinded_planchet (void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) +{ + const struct TALER_BlindedPlanchet *bp = data; + size_t tlen; + size_t len; + uint32_t be[2]; + char *buf; + + (void) cls; + (void) data_len; + GNUNET_assert (1 == param_length); + GNUNET_assert (scratch_length > 0); + GNUNET_break (NULL == cls); + be[0] = htonl ((uint32_t) bp->cipher); + be[1] = htonl (0x0100); /* magic marker: blinded */ + switch (bp->cipher) + { + case TALER_DENOMINATION_RSA: + tlen = bp->details.rsa_blinded_planchet.blinded_msg_size; + break; + case TALER_DENOMINATION_CS: + tlen = sizeof (bp->details.cs_blinded_planchet); + break; + default: + GNUNET_assert (0); + } + len = tlen + sizeof (be); + buf = GNUNET_malloc (len); + memcpy (buf, + &be, + sizeof (be)); + switch (bp->cipher) + { + case TALER_DENOMINATION_RSA: + memcpy (&buf[sizeof (be)], + bp->details.rsa_blinded_planchet.blinded_msg, + tlen); + break; + case TALER_DENOMINATION_CS: + memcpy (&buf[sizeof (be)], + &bp->details.cs_blinded_planchet, + tlen); + break; + default: + GNUNET_assert (0); + } + scratch[0] = buf; + param_values[0] = (void *) buf; + param_lengths[0] = len; + param_formats[0] = 1; + return 1; +} + + +struct GNUNET_PQ_QueryParam +TALER_PQ_query_param_blinded_planchet ( + const struct TALER_BlindedPlanchet *bp) +{ + struct GNUNET_PQ_QueryParam res = { + .conv = &qconv_blinded_planchet, + .data = bp, + .num_params = 1 + }; + + return res; +} + + +/** + * Function called to convert input argument into SQL parameters. + * + * @param cls closure + * @param data pointer to input argument + * @param data_len number of bytes in @a data (if applicable) + * @param[out] param_values SQL data to set + * @param[out] param_lengths SQL length data to set + * @param[out] param_formats SQL format data to set + * @param param_length number of entries available in the @a param_values, @a param_lengths and @a param_formats arrays + * @param[out] scratch buffer for dynamic allocations (to be done via #GNUNET_malloc() + * @param scratch_length number of entries left in @a scratch + * @return -1 on error, number of offsets used in @a scratch otherwise + */ +static int +qconv_exchange_withdraw_values (void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) +{ + const struct TALER_ExchangeWithdrawValues *alg_values = data; + size_t tlen; + size_t len; + uint32_t be[2]; + char *buf; + + (void) cls; + (void) data_len; + GNUNET_assert (1 == param_length); + GNUNET_assert (scratch_length > 0); + GNUNET_break (NULL == cls); + be[0] = htonl ((uint32_t) alg_values->cipher); + be[1] = htonl (0x010000); /* magic marker: EWV */ + switch (alg_values->cipher) + { + case TALER_DENOMINATION_RSA: + tlen = 0; + break; + case TALER_DENOMINATION_CS: + tlen = sizeof (struct TALER_DenominationCSPublicRPairP); + break; + default: + GNUNET_assert (0); + } + len = tlen + sizeof (be); + buf = GNUNET_malloc (len); + memcpy (buf, + &be, + sizeof (be)); + switch (alg_values->cipher) + { + case TALER_DENOMINATION_RSA: + break; + case TALER_DENOMINATION_CS: + memcpy (&buf[sizeof (be)], + &alg_values->details.cs_values, + tlen); + break; + default: + GNUNET_assert (0); + } + scratch[0] = buf; + param_values[0] = (void *) buf; + param_lengths[0] = len; + param_formats[0] = 1; + return 1; +} + + +struct GNUNET_PQ_QueryParam +TALER_PQ_query_param_exchange_withdraw_values ( + const struct TALER_ExchangeWithdrawValues *alg_values) +{ + struct GNUNET_PQ_QueryParam res = { + .conv = &qconv_exchange_withdraw_values, + .data = alg_values, + .num_params = 1 + }; + + return res; +} + + /** * Function called to convert input argument into SQL parameters. * diff --git a/src/pq/pq_result_helper.c b/src/pq/pq_result_helper.c index a6bc9409a..1115a130c 100644 --- a/src/pq/pq_result_helper.c +++ b/src/pq/pq_result_helper.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014, 2015, 2016, 2021 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -357,7 +357,7 @@ TALER_PQ_result_spec_json (const char *name, * * @param cls closure * @param result where to extract data from - * @param int row to extract data from + * @param row the row to extract data from * @param fname name (or prefix) of the fields to extract from * @param[in,out] dst_size where to store size of result, may be NULL * @param[out] dst where to store the result @@ -425,7 +425,16 @@ extract_denom_pub (void *cls, return GNUNET_SYSERR; } return GNUNET_OK; - // FIXME: add CS case! + case TALER_DENOMINATION_CS: + if (sizeof (pk->details.cs_public_key) != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&pk->details.cs_public_key, + res, + len); + return GNUNET_OK; default: GNUNET_break (0); } @@ -471,7 +480,7 @@ TALER_PQ_result_spec_denom_pub (const char *name, * * @param cls closure * @param result where to extract data from - * @param int row to extract data from + * @param row the row to extract data from * @param fname name (or prefix) of the fields to extract from * @param[in,out] dst_size where to store size of result, may be NULL * @param[out] dst where to store the result @@ -543,7 +552,16 @@ extract_denom_sig (void *cls, return GNUNET_SYSERR; } return GNUNET_OK; - // FIXME: add CS case! + case TALER_DENOMINATION_CS: + if (sizeof (sig->details.cs_signature) != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&sig->details.cs_signature, + res, + len); + return GNUNET_OK; default: GNUNET_break (0); } @@ -589,7 +607,7 @@ TALER_PQ_result_spec_denom_sig (const char *name, * * @param cls closure * @param result where to extract data from - * @param int row to extract data from + * @param row the row to extract data from * @param fname name (or prefix) of the fields to extract from * @param[in,out] dst_size where to store size of result, may be NULL * @param[out] dst where to store the result @@ -661,7 +679,16 @@ extract_blinded_denom_sig (void *cls, return GNUNET_SYSERR; } return GNUNET_OK; - // FIXME: add CS case! + case TALER_DENOMINATION_CS: + if (sizeof (sig->details.blinded_cs_answer) != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&sig->details.blinded_cs_answer, + res, + len); + return GNUNET_OK; default: GNUNET_break (0); } @@ -703,4 +730,235 @@ TALER_PQ_result_spec_blinded_denom_sig ( } +/** + * Extract data from a Postgres database @a result at row @a row. + * + * @param cls closure + * @param result where to extract data from + * @param row the row to extract data from + * @param fname name (or prefix) of the fields to extract from + * @param[in,out] dst_size where to store size of result, may be NULL + * @param[out] dst where to store the result + * @return + * #GNUNET_YES if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ +static enum GNUNET_GenericReturnValue +extract_blinded_planchet (void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) +{ + struct TALER_BlindedPlanchet *bp = dst; + size_t len; + const char *res; + int fnum; + uint32_t be[2]; + + (void) cls; + (void) dst_size; + fnum = PQfnumber (result, + fname); + if (fnum < 0) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + if (PQgetisnull (result, + row, + fnum)) + return GNUNET_NO; + + /* if a field is null, continue but + * remember that we now return a different result */ + len = PQgetlength (result, + row, + fnum); + res = PQgetvalue (result, + row, + fnum); + if (len < sizeof (be)) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&be, + res, + sizeof (be)); + if (0x0100 != ntohl (be[1])) /* magic marker: blinded */ + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + res += sizeof (be); + len -= sizeof (be); + bp->cipher = ntohl (be[0]); + switch (bp->cipher) + { + case TALER_DENOMINATION_RSA: + bp->details.rsa_blinded_planchet.blinded_msg_size + = len; + bp->details.rsa_blinded_planchet.blinded_msg + = GNUNET_memdup (res, + len); + return GNUNET_OK; + case TALER_DENOMINATION_CS: + if (sizeof (bp->details.cs_blinded_planchet) != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&bp->details.cs_blinded_planchet, + res, + len); + return GNUNET_OK; + default: + GNUNET_break (0); + } + return GNUNET_SYSERR; +} + + +/** + * Function called to clean up memory allocated + * by a #GNUNET_PQ_ResultConverter. + * + * @param cls closure + * @param rd result data to clean up + */ +static void +clean_blinded_planchet (void *cls, + void *rd) +{ + struct TALER_BlindedPlanchet *bp = rd; + + (void) cls; + TALER_blinded_planchet_free (bp); +} + + +struct GNUNET_PQ_ResultSpec +TALER_PQ_result_spec_blinded_planchet ( + const char *name, + struct TALER_BlindedPlanchet *bp) +{ + struct GNUNET_PQ_ResultSpec res = { + .conv = &extract_blinded_planchet, + .cleaner = &clean_blinded_planchet, + .dst = (void *) bp, + .fname = name + }; + + return res; +} + + +/** + * Extract data from a Postgres database @a result at row @a row. + * + * @param cls closure + * @param result where to extract data from + * @param row row to extract data from + * @param fname name (or prefix) of the fields to extract from + * @param[in,out] dst_size where to store size of result, may be NULL + * @param[out] dst where to store the result + * @return + * #GNUNET_YES if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ +static enum GNUNET_GenericReturnValue +extract_exchange_withdraw_values (void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) +{ + struct TALER_ExchangeWithdrawValues *alg_values = dst; + size_t len; + const char *res; + int fnum; + uint32_t be[2]; + + (void) cls; + (void) dst_size; + fnum = PQfnumber (result, + fname); + if (fnum < 0) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + if (PQgetisnull (result, + row, + fnum)) + return GNUNET_NO; + + /* if a field is null, continue but + * remember that we now return a different result */ + len = PQgetlength (result, + row, + fnum); + res = PQgetvalue (result, + row, + fnum); + if (len < sizeof (be)) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&be, + res, + sizeof (be)); + if (0x010000 != ntohl (be[1])) /* magic marker: EWV */ + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + res += sizeof (be); + len -= sizeof (be); + alg_values->cipher = ntohl (be[0]); + switch (alg_values->cipher) + { + case TALER_DENOMINATION_RSA: + if (0 != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + case TALER_DENOMINATION_CS: + if (sizeof (struct TALER_DenominationCSPublicRPairP) != len) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + memcpy (&alg_values->details.cs_values, + res, + len); + return GNUNET_OK; + default: + GNUNET_break (0); + } + return GNUNET_SYSERR; +} + + +struct GNUNET_PQ_ResultSpec +TALER_PQ_result_spec_exchange_withdraw_values ( + const char *name, + struct TALER_ExchangeWithdrawValues *ewv) +{ + struct GNUNET_PQ_ResultSpec res = { + .conv = &extract_exchange_withdraw_values, + .dst = (void *) ewv, + .fname = name + }; + + return res; +} + + /* end of pq_result_helper.c */ diff --git a/src/testing/.gitignore b/src/testing/.gitignore index 8c19b94c8..71fe5c474 100644 --- a/src/testing/.gitignore +++ b/src/testing/.gitignore @@ -1,13 +1,16 @@ -test_auditor_api_version +test_auditor_api_version_cs +test_auditor_api_version_rsa test_bank_api_with_fakebank test_bank_api_with_fakebank_twisted test_bank_api_with_pybank test_bank_api_with_pybank_twisted test_taler_exchange_aggregator-postgres test_taler_exchange_wirewatch-postgres -test_exchange_api_revocation +test_exchange_api_revocation_cs +test_exchange_api_revocation_rsa report* -test_exchange_management_api +test_exchange_management_api_cs +test_exchange_management_api_rsa test_exchange_api_home/.local/share/taler/crypto-eddsa/ test_exchange_api_home/.local/share/taler/crypto-rsa/ test_exchange_api_home/.local/share/taler/exchange/offline-keys/secm_tofus.priv @@ -24,12 +27,20 @@ test_taler_exchange_httpd_home/.local/share/taler/taler-exchange-secmod-eddsa/ test_taler_exchange_httpd_home/.local/share/taler/taler-exchange-secmod-rsa/ test_exchange_api_keys_cherry_picking_home/.local/share/taler/crypto-rsa/ test_exchange_api_home/.local/share/taler/exchange-offline/secm_tofus.pub +test_exchange_api_home/.local/share/taler/exchange-secmod-cs/ test_exchange_api_home/.local/share/taler/exchange-secmod-eddsa/ test_exchange_api_home/.local/share/taler/exchange-secmod-rsa/ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange-offline/secm_tofus.pub +test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange-secmod-cs/ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange-secmod-eddsa/ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange-secmod-rsa/ test_taler_exchange_httpd_home/.local/share/taler/exchange-offline/secm_tofus.pub +test_taler_exchange_httpd_home/.local/share/taler/exchange-secmod-cs/ test_taler_exchange_httpd_home/.local/share/taler/exchange-secmod-eddsa/ test_taler_exchange_httpd_home/.local/share/taler/exchange-secmod-rsa/ test_kyc_api +test_helper_cs_home/ +test_helper_rsa_home/test_exchange_api_twisted-cs +test_exchange_api_twisted-rsa +test_exchange_api_twisted_cs +test_exchange_api_twisted_rsa diff --git a/src/testing/Makefile.am b/src/testing/Makefile.am index 5b9e0294d..9e6a5244f 100644 --- a/src/testing/Makefile.am +++ b/src/testing/Makefile.am @@ -115,22 +115,30 @@ AM_TESTS_ENVIRONMENT=export TALER_PREFIX=$${TALER_PREFIX:-@libdir@};export PATH= .NOTPARALLEL: check_PROGRAMS = \ - test_auditor_api \ - test_auditor_api_version \ + test_auditor_api_cs \ + test_auditor_api_rsa \ + test_auditor_api_version_rsa \ + test_auditor_api_version_cs \ test_bank_api_with_fakebank \ test_bank_api_with_pybank \ test_bank_api_with_nexus \ - test_exchange_api \ - test_exchange_api_keys_cherry_picking \ - test_exchange_api_revocation \ - test_exchange_api_overlapping_keys_bug \ - test_exchange_management_api \ + test_exchange_api_cs \ + test_exchange_api_rsa \ + test_exchange_api_keys_cherry_picking_cs \ + test_exchange_api_keys_cherry_picking_rsa \ + test_exchange_api_revocation_cs \ + test_exchange_api_revocation_rsa \ + test_exchange_api_overlapping_keys_bug_cs \ + test_exchange_api_overlapping_keys_bug_rsa \ + test_exchange_management_api_cs \ + test_exchange_management_api_rsa \ test_kyc_api \ test_taler_exchange_aggregator-postgres \ test_taler_exchange_wirewatch-postgres if HAVE_TWISTER check_PROGRAMS += \ - test_exchange_api_twisted \ + test_exchange_api_twisted_cs \ + test_exchange_api_twisted_rsa \ test_bank_api_with_fakebank_twisted \ test_bank_api_with_pybank_twisted endif @@ -140,9 +148,9 @@ endif TESTS = \ $(check_PROGRAMS) -test_auditor_api_SOURCES = \ +test_auditor_api_cs_SOURCES = \ test_auditor_api.c -test_auditor_api_LDADD = \ +test_auditor_api_cs_LDADD = \ $(top_builddir)/src/lib/libtalerauditor.la \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerexchange.la \ @@ -151,19 +159,51 @@ test_auditor_api_LDADD = \ $(top_builddir)/src/bank-lib/libtalerbank.la \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_auditor_api_rsa_SOURCES = \ + test_auditor_api.c +test_auditor_api_rsa_LDADD = \ + $(top_builddir)/src/lib/libtalerauditor.la \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/bank-lib/libtalerfakebank.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ $(XLIB) -test_auditor_api_version_SOURCES = \ +test_auditor_api_version_cs_SOURCES = \ test_auditor_api_version.c -test_auditor_api_version_LDADD = \ +test_auditor_api_version_cs_LDADD = \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerauditor.la \ $(LIBGCRYPT_LIBS) \ $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_auditor_api_version_rsa_SOURCES = \ + test_auditor_api_version.c +test_auditor_api_version_rsa_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerauditor.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ @@ -196,9 +236,9 @@ test_bank_api_with_pybank_LDADD = \ $(top_builddir)/src/bank-lib/libtalerbank.la \ $(XLIB) -test_exchange_api_SOURCES = \ +test_exchange_api_cs_SOURCES = \ test_exchange_api.c -test_exchange_api_LDADD = \ +test_exchange_api_cs_LDADD = \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerexchange.la \ $(LIBGCRYPT_LIBS) \ @@ -206,24 +246,16 @@ test_exchange_api_LDADD = \ $(top_builddir)/src/bank-lib/libtalerbank.la \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ -ltalerextensions \ $(XLIB) -test_exchange_management_api_SOURCES = \ - test_exchange_management_api.c -test_exchange_management_api_LDADD = \ - libtalertesting.la \ - $(top_builddir)/src/lib/libtalerexchange.la \ - $(top_builddir)/src/util/libtalerutil.la \ - -lgnunetutil \ - $(XLIB) - -test_exchange_api_revocation_SOURCES = \ - test_exchange_api_revocation.c -test_exchange_api_revocation_LDADD = \ +test_exchange_api_rsa_SOURCES = \ + test_exchange_api.c +test_exchange_api_rsa_LDADD = \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerexchange.la \ $(LIBGCRYPT_LIBS) \ @@ -231,39 +263,126 @@ test_exchange_api_revocation_LDADD = \ $(top_builddir)/src/bank-lib/libtalerbank.la \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ $(XLIB) -test_exchange_api_keys_cherry_picking_SOURCES = \ +test_exchange_api_keys_cherry_picking_cs_SOURCES = \ test_exchange_api_keys_cherry_picking.c -test_exchange_api_keys_cherry_picking_LDADD = \ +test_exchange_api_keys_cherry_picking_cs_LDADD = \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerexchange.la \ $(LIBGCRYPT_LIBS) \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ $(top_builddir)/src/bank-lib/libtalerbank.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ $(XLIB) -test_exchange_api_overlapping_keys_bug_SOURCES = \ - test_exchange_api_overlapping_keys_bug.c -test_exchange_api_overlapping_keys_bug_LDADD = \ +test_exchange_api_keys_cherry_picking_rsa_SOURCES = \ + test_exchange_api_keys_cherry_picking.c +test_exchange_api_keys_cherry_picking_rsa_LDADD = \ libtalertesting.la \ $(top_builddir)/src/lib/libtalerexchange.la \ $(LIBGCRYPT_LIBS) \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ $(top_builddir)/src/bank-lib/libtalerbank.la \ + -lgnunettesting \ -lgnunetcurl \ -lgnunetutil \ -ljansson \ $(XLIB) +test_exchange_api_revocation_cs_SOURCES = \ + test_exchange_api_revocation.c +test_exchange_api_revocation_cs_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/bank-lib/libtalerfakebank.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_exchange_api_revocation_rsa_SOURCES = \ + test_exchange_api_revocation.c +test_exchange_api_revocation_rsa_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/bank-lib/libtalerfakebank.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + + +test_exchange_api_overlapping_keys_bug_cs_SOURCES = \ + test_exchange_api_overlapping_keys_bug.c +test_exchange_api_overlapping_keys_bug_cs_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_exchange_api_overlapping_keys_bug_rsa_SOURCES = \ + test_exchange_api_overlapping_keys_bug.c +test_exchange_api_overlapping_keys_bug_rsa_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(LIBGCRYPT_LIBS) \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + -lgnunettesting \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_exchange_management_api_cs_SOURCES = \ + test_exchange_management_api.c +test_exchange_management_api_cs_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetutil \ + $(XLIB) + +test_exchange_management_api_rsa_SOURCES = \ + test_exchange_management_api.c +test_exchange_management_api_rsa_LDADD = \ + libtalertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetutil \ + $(XLIB) + + test_taler_exchange_aggregator_postgres_SOURCES = \ test_taler_exchange_aggregator.c test_taler_exchange_aggregator_postgres_LDADD = \ @@ -297,9 +416,9 @@ test_taler_exchange_wirewatch_postgres_LDADD = \ -lpthread \ $(XLIB) -test_exchange_api_twisted_SOURCES = \ +test_exchange_api_twisted_cs_SOURCES = \ test_exchange_api_twisted.c -test_exchange_api_twisted_LDADD = \ +test_exchange_api_twisted_cs_LDADD = \ $(LIBGCRYPT_LIBS) \ libtalertesting.la \ libtalertwistertesting.la \ @@ -308,6 +427,25 @@ test_exchange_api_twisted_LDADD = \ $(top_builddir)/src/bank-lib/libtalerbank.la \ $(top_builddir)/src/json/libtalerjson.la \ $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ + -lgnunetjson \ + -lgnunetcurl \ + -lgnunetutil \ + -ljansson \ + $(XLIB) + +test_exchange_api_twisted_rsa_SOURCES = \ + test_exchange_api_twisted.c +test_exchange_api_twisted_rsa_LDADD = \ + $(LIBGCRYPT_LIBS) \ + libtalertesting.la \ + libtalertwistertesting.la \ + $(top_builddir)/src/lib/libtalerexchange.la \ + $(top_builddir)/src/bank-lib/libtalerfakebank.la \ + $(top_builddir)/src/bank-lib/libtalerbank.la \ + $(top_builddir)/src/json/libtalerjson.la \ + $(top_builddir)/src/util/libtalerutil.la \ + -lgnunettesting \ -lgnunetjson \ -lgnunetcurl \ -lgnunetutil \ @@ -323,6 +461,7 @@ test_bank_api_with_fakebank_twisted_LDADD = \ $(top_builddir)/src/lib/libtalerexchange.la \ $(top_builddir)/src/json/libtalerjson.la \ libtalertwistertesting.la \ + -lgnunettesting \ -lgnunetjson \ -lgnunetcurl \ -lgnunetutil \ @@ -338,6 +477,7 @@ test_bank_api_with_pybank_twisted_LDADD = \ $(top_builddir)/src/lib/libtalerexchange.la \ $(top_builddir)/src/json/libtalerjson.la \ libtalertwistertesting.la \ + -lgnunettesting \ -lgnunetjson \ -lgnunetcurl \ -lgnunetutil \ @@ -365,7 +505,8 @@ test_kyc_api_LDADD = \ EXTRA_DIST = \ test_auditor_api.conf \ - test_auditor_api_expire_reserve_now.conf \ + test_auditor_api_expire_reserve_now-cs.conf \ + test_auditor_api_expire_reserve_now-rsa.conf \ test_bank_api_fakebank.conf \ test_bank_api_fakebank_twisted.conf \ test_bank_api_pybank.conf \ @@ -378,10 +519,14 @@ EXTRA_DIST = \ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange-offline/master.priv \ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange/offline-keys/master.priv \ test_exchange_api_keys_cherry_picking_home/.local/share/taler/exchange/wirefees/x-taler-bank.fee \ - test_exchange_api.conf \ - test_exchange_api_twisted.conf \ - test_exchange_api_keys_cherry_picking.conf \ - test_exchange_api_expire_reserve_now.conf \ + test_exchange_api-cs.conf \ + test_exchange_api-rsa.conf \ + test_exchange_api_twisted-cs.conf \ + test_exchange_api_twisted-rsa.conf \ + test_exchange_api_keys_cherry_picking-cs.conf \ + test_exchange_api_keys_cherry_picking-rsa.conf \ + test_exchange_api_expire_reserve_now-cs.conf \ + test_exchange_api_expire_reserve_now-rsa.conf \ test_taler_exchange_httpd_home/.config/taler/account-1.json \ test_taler_exchange_httpd_home/.local/share/taler/exchange-offline/master.priv \ test_taler_exchange_httpd_home/.local/share/taler/exchange/offline-keys/master.priv \ diff --git a/src/testing/test-taler-exchange-aggregator-postgres.conf b/src/testing/test-taler-exchange-aggregator-postgres.conf index 7f277629d..dfa017d0d 100644 --- a/src/testing/test-taler-exchange-aggregator-postgres.conf +++ b/src/testing/test-taler-exchange-aggregator-postgres.conf @@ -92,4 +92,5 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 diff --git a/src/testing/test-taler-exchange-wirewatch-postgres.conf b/src/testing/test-taler-exchange-wirewatch-postgres.conf index d42f9d445..fda1acd77 100644 --- a/src/testing/test-taler-exchange-wirewatch-postgres.conf +++ b/src/testing/test-taler-exchange-wirewatch-postgres.conf @@ -81,4 +81,5 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 diff --git a/src/testing/test_auditor_api-cs.conf b/src/testing/test_auditor_api-cs.conf new file mode 100644 index 000000000..fbd84461d --- /dev/null +++ b/src/testing/test_auditor_api-cs.conf @@ -0,0 +1,140 @@ + +# This file is in the public domain. +# +[PATHS] +# Persistent data storage for the testcase +TALER_TEST_HOME = test_exchange_api_home/ +TALER_RUNTIME_DIR = ${TMPDIR:-${TMP:-/tmp}}/${USER:-}/taler-system-runtime/ + +[taler-exchange-secmod-cs] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days + +[taler-exchange-secmod-eddsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days +# Reduce from 12 weeks to ensure we have multiple +DURATION = 14 days + + +[taler] +# Currency supported by the exchange (can only be one) +CURRENCY = EUR +CURRENCY_ROUND_UNIT = EUR:0.01 + +[auditor] +BASE_URL = "http://localhost:8083/" + +# HTTP port the auditor listens to +PORT = 8083 + +TINY_AMOUNT = EUR:0.01 + +[exchange] + +# HTTP port the exchange listens to +PORT = 8081 + +# Master public key used to sign the exchange's various keys +MASTER_PUBLIC_KEY = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG + +# How to access our database +DB = postgres + +# Base URL of the exchange. Must be set to a URL where the +# exchange (or the twister) is actually listening. +BASE_URL = "http://localhost:8081/" + +[exchangedb-postgres] +CONFIG = "postgres:///talercheck" + +[auditordb-postgres] +CONFIG = "postgres:///talercheck" + +# Sections starting with "exchange-account-" configure the bank accounts +# of the exchange. The "URL" specifies the account in +# payto://-format. +[exchange-account-1] +# What is the URL of our account? +PAYTO_URI = "payto://x-taler-bank/localhost/42" + +[exchange-accountcredentials-1] +WIRE_GATEWAY_URL = "http://localhost:8082/42/" + +[bank] +HTTP_PORT = 8082 + +# ENABLE_CREDIT = YES + +[exchange-account-2] +# What is the bank account (with the "Taler Bank" demo system)? +PAYTO_URI = "payto://x-taler-bank/localhost/2" +ENABLE_DEBIT = YES +ENABLE_CREDIT = YES + +# Authentication information for basic authentication +[exchange-accountcredentials-2] +WIRE_GATEWAY_URL = "http://localhost:8082/2/" +WIRE_GATEWAY_AUTH_METHOD = "basic" +USERNAME = user +PASSWORD = pass + + + + +# Sections starting with "coin_" specify which denominations +# the exchange should support (and their respective fee structure) +[coin_eur_ct_1] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_5] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_10] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/testing/test_auditor_api.conf b/src/testing/test_auditor_api-rsa.conf similarity index 97% rename from src/testing/test_auditor_api.conf rename to src/testing/test_auditor_api-rsa.conf index 03a5e2453..95eb47b38 100644 --- a/src/testing/test_auditor_api.conf +++ b/src/testing/test_auditor_api-rsa.conf @@ -93,6 +93,7 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_ct_10] @@ -104,6 +105,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_1] @@ -115,6 +117,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_5] @@ -126,6 +129,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_10] @@ -137,4 +141,5 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 diff --git a/src/testing/test_auditor_api.c b/src/testing/test_auditor_api.c index f748ac291..9ab78664d 100644 --- a/src/testing/test_auditor_api.c +++ b/src/testing/test_auditor_api.c @@ -29,6 +29,7 @@ #include "taler_auditor_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -39,10 +40,9 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_auditor_api.conf" +static char *config_file; -#define CONFIG_FILE_EXPIRE_RESERVE_NOW \ - "test_auditor_api_expire_reserve_now.conf" +static char *config_file_expire_reserve_now; /** * Exchange configuration data. @@ -61,7 +61,7 @@ static struct TALER_TESTING_BankConfiguration bc; * @param label label to use for the command. */ #define CMD_EXEC_WIREWATCH(label) \ - TALER_TESTING_cmd_exec_wirewatch (label, CONFIG_FILE) + TALER_TESTING_cmd_exec_wirewatch (label, config_file) /** * Execute the taler-exchange-aggregator, closer and transfer commands with @@ -71,8 +71,8 @@ static struct TALER_TESTING_BankConfiguration bc; */ #define CMD_EXEC_AGGREGATOR(label) \ TALER_TESTING_cmd_sleep (label "-sleep", 1), \ - TALER_TESTING_cmd_exec_aggregator (label, CONFIG_FILE), \ - TALER_TESTING_cmd_exec_transfer (label, CONFIG_FILE) + TALER_TESTING_cmd_exec_aggregator (label, config_file), \ + TALER_TESTING_cmd_exec_transfer (label, config_file) /** * Run wire transfer of funds from some user's account to the @@ -92,7 +92,7 @@ static struct TALER_TESTING_BankConfiguration bc; * @param label label to use for the command. */ #define CMD_RUN_AUDITOR(label) \ - TALER_TESTING_cmd_exec_auditor (label, CONFIG_FILE) + TALER_TESTING_cmd_exec_auditor (label, config_file) /** @@ -186,7 +186,7 @@ run (void *cls, /** * Melt the rest of the coin's value (EUR:4.00 = 3x EUR:1.03 + 7x * EUR:0.13) -*/ + */ TALER_TESTING_cmd_melt_double ("refresh-melt-1", "refresh-withdraw-coin-1", MHD_HTTP_OK, @@ -411,7 +411,7 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-1", MHD_HTTP_OK, "recoup-withdraw-coin-1", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_recoup ("recoup-1", MHD_HTTP_OK, "recoup-withdraw-coin-1", @@ -432,9 +432,9 @@ run (void *cls, CMD_TRANSFER_TO_EXCHANGE ("short-lived-reserve", "EUR:5.01"), TALER_TESTING_cmd_exec_wirewatch ("short-lived-aggregation", - CONFIG_FILE_EXPIRE_RESERVE_NOW), + config_file_expire_reserve_now), TALER_TESTING_cmd_exec_aggregator ("close-reserves", - CONFIG_FILE_EXPIRE_RESERVE_NOW), + config_file_expire_reserve_now), /** * Fill reserve with EUR:2.02, as withdraw fee is 1 ct per * config, then withdraw two coin, partially spend one, and @@ -474,7 +474,7 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-2", MHD_HTTP_OK, "recoup-withdraw-coin-2a", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_recoup ("recoup-2", MHD_HTTP_OK, "recoup-withdraw-coin-2a", @@ -649,7 +649,7 @@ run (void *cls, struct TALER_TESTING_Command commands[] = { TALER_TESTING_cmd_exec_offline_sign_fees ("offline-sign-fees", - CONFIG_FILE, + config_file, "EUR:0.01", "EUR:0.01"), TALER_TESTING_cmd_auditor_add ("add-auditor-OK", @@ -660,11 +660,11 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", 2), TALER_TESTING_cmd_exec_auditor_offline ("auditor-offline", - CONFIG_FILE), + config_file), CMD_RUN_AUDITOR ("virgin-auditor"), TALER_TESTING_cmd_exchanges_with_url ("check-exchange", MHD_HTTP_OK, @@ -700,25 +700,36 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-auditor-api", + GNUNET_log_setup (argv[0], "INFO", NULL); + + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_auditor_api-%s.conf", + cipher); + GNUNET_asprintf (&config_file_expire_reserve_now, + "test_auditor_api_expire_reserve_now-%s.conf", + cipher); + GNUNET_free (cipher); /* Check fakebank port is available and get configuration data. */ if (GNUNET_OK != - TALER_TESTING_prepare_fakebank (CONFIG_FILE, + TALER_TESTING_prepare_fakebank (config_file, "exchange-account-2", &bc)) return 77; - TALER_TESTING_cleanup_files (CONFIG_FILE); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Run keyup, create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -735,7 +746,7 @@ main (int argc, */ TALER_TESTING_auditor_setup (&run, NULL, - CONFIG_FILE)) + config_file)) return 2; break; default: diff --git a/src/testing/test_exchange_api_expire_reserve_now.conf b/src/testing/test_auditor_api_expire_reserve_now-cs.conf similarity index 59% rename from src/testing/test_exchange_api_expire_reserve_now.conf rename to src/testing/test_auditor_api_expire_reserve_now-cs.conf index 05bca956b..7277a0dff 100644 --- a/src/testing/test_exchange_api_expire_reserve_now.conf +++ b/src/testing/test_auditor_api_expire_reserve_now-cs.conf @@ -1,4 +1,4 @@ -@INLINE@ test_exchange_api.conf +@INLINE@ test_auditor_api-cs.conf [exchangedb] IDLE_RESERVE_EXPIRATION_TIME = 0 s diff --git a/src/testing/test_auditor_api_expire_reserve_now.conf b/src/testing/test_auditor_api_expire_reserve_now-rsa.conf similarity index 58% rename from src/testing/test_auditor_api_expire_reserve_now.conf rename to src/testing/test_auditor_api_expire_reserve_now-rsa.conf index c2bf8f479..788cc36f8 100644 --- a/src/testing/test_auditor_api_expire_reserve_now.conf +++ b/src/testing/test_auditor_api_expire_reserve_now-rsa.conf @@ -1,4 +1,4 @@ -@INLINE@ test_auditor_api.conf +@INLINE@ test_auditor_api-rsa.conf [exchangedb] IDLE_RESERVE_EXPIRATION_TIME = 0 s diff --git a/src/testing/test_exchange_api-cs.conf b/src/testing/test_exchange_api-cs.conf new file mode 100644 index 000000000..3fbf4c3c3 --- /dev/null +++ b/src/testing/test_exchange_api-cs.conf @@ -0,0 +1,201 @@ +# This file is in the public domain. +# + +[PATHS] +# Persistent data storage for the testcase +TALER_TEST_HOME = test_exchange_api_home/ +TALER_RUNTIME_DIR = ${TMPDIR:-${TMP:-/tmp}}/${USER:-}/taler-system-runtime/ + +[taler-exchange-secmod-rsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days + +[taler-exchange-secmod-eddsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days +# Reduce from 12 weeks to ensure we have multiple +DURATION = 14 days + +[taler] +# Currency supported by the exchange (can only be one) +CURRENCY = EUR +CURRENCY_ROUND_UNIT = EUR:0.01 + +[auditor] +BASE_URL = "http://localhost:8083/" + +# HTTP port the auditor listens to +PORT = 8083 + +[exchange] + +TERMS_ETAG = 0 +PRIVACY_ETAG = 0 + +# HTTP port the exchange listens to +PORT = 8081 + +# Master public key used to sign the exchange's various keys +MASTER_PUBLIC_KEY = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG + +# How to access our database +DB = postgres + +# Base URL of the exchange. Must be set to a URL where the +# exchange (or the twister) is actually listening. +BASE_URL = "http://localhost:8081/" + +[exchangedb-postgres] +CONFIG = "postgres:///talercheck" + +[auditordb-postgres] +CONFIG = "postgres:///talercheck" + +# Sections starting with "exchange-account-" configure the bank accounts +# of the exchange. The "URL" specifies the account in +# payto://-format. +[exchange-account-1] +# What is the URL of our account? +PAYTO_URI = "payto://x-taler-bank/localhost/42" +# ENABLE_CREDIT = YES + +[exchange-accountcredentials-1] +WIRE_GATEWAY_URL = "http://localhost:9081/42/" + +[exchange-account-2] +# What is the bank account (with the "Taler Bank" demo system)? +PAYTO_URI = "payto://x-taler-bank/localhost/2" +ENABLE_DEBIT = YES +ENABLE_CREDIT = YES + +[exchange-accountcredentials-2] +WIRE_GATEWAY_AUTH_METHOD = basic +USERNAME = Exchange +PASSWORD = x +WIRE_GATEWAY_URL = "http://localhost:9081/2/" + +[bank] +HTTP_PORT = 9081 + +# Enabled extensions +[exchange-extension-age_restriction] +ENABLED = YES +# default age groups: +#AGE_GROUPS = "8:10:12:14:16:18:21" + +# Sections starting with "coin_" specify which denominations +# the exchange should support (and their respective fee structure) +[coin_eur_ct_1] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_5] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_10] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_1_age_restricted] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +age_restricted = true +CIPHER = CS + +[coin_eur_ct_10_age_restricted] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +age_restricted = true +CIPHER = CS + +[coin_eur_1_age_restricted] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +age_restricted = true +CIPHER = CS + +[coin_eur_5_age_restricted] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +age_restricted = true +CIPHER = CS + +[coin_eur_10_age_restricted] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +age_restricted = true +CIPHER = CS diff --git a/src/testing/test_exchange_api.conf b/src/testing/test_exchange_api-rsa.conf similarity index 97% rename from src/testing/test_exchange_api.conf rename to src/testing/test_exchange_api-rsa.conf index 6bb7bd59f..1d4456623 100644 --- a/src/testing/test_exchange_api.conf +++ b/src/testing/test_exchange_api-rsa.conf @@ -94,6 +94,7 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_ct_10] @@ -105,6 +106,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_1] @@ -116,6 +118,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_5] @@ -127,6 +130,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_10] @@ -138,6 +142,7 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 [coin_eur_ct_1_age_restricted] @@ -151,6 +156,7 @@ fee_refresh = EUR:0.01 fee_refund = EUR:0.01 rsa_keysize = 1024 age_restricted = YES +CIPHER = RSA [coin_eur_ct_10_age_restricted] value = EUR:0.10 @@ -163,6 +169,7 @@ fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 age_restricted = YES +CIPHER = RSA [coin_eur_1_age_restricted] value = EUR:1 @@ -175,6 +182,7 @@ fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 age_restricted = YES +CIPHER = RSA [coin_eur_5_age_restricted] value = EUR:5 @@ -187,6 +195,7 @@ fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 age_restricted = YES +CIPHER = RSA [coin_eur_10_age_restricted] value = EUR:10 @@ -199,3 +208,4 @@ fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 age_restricted = YES +CIPHER = RSA diff --git a/src/testing/test_exchange_api.c b/src/testing/test_exchange_api.c index 0348b265c..8e1a5b35b 100644 --- a/src/testing/test_exchange_api.c +++ b/src/testing/test_exchange_api.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014--2020 Taler Systems SA + Copyright (C) 2014--2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as @@ -29,6 +29,7 @@ #include "taler_exchange_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -39,11 +40,13 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api.conf" - -#define CONFIG_FILE_EXPIRE_RESERVE_NOW \ - "test_exchange_api_expire_reserve_now.conf" +static char *config_file; +/** + * Special configuration file to use when we want reserves + * to expire 'immediately'. + */ +static char *config_file_expire_reserve_now; /** * Exchange configuration data. @@ -55,6 +58,14 @@ static struct TALER_TESTING_ExchangeConfiguration ec; */ static struct TALER_TESTING_BankConfiguration bc; +/** + * Some tests behave differently when using CS as we cannot + * re-use the coin private key for different denominations + * due to the derivation of it with the /csr values. Hence + * some tests behave differently in CS mode, hence this + * flag. + */ +static bool uses_cs; /** * Execute the taler-exchange-wirewatch command with @@ -63,7 +74,7 @@ static struct TALER_TESTING_BankConfiguration bc; * @param label label to use for the command. */ #define CMD_EXEC_WIREWATCH(label) \ - TALER_TESTING_cmd_exec_wirewatch (label, CONFIG_FILE) + TALER_TESTING_cmd_exec_wirewatch (label, config_file) /** * Execute the taler-exchange-aggregator, closer and transfer commands with @@ -72,8 +83,8 @@ static struct TALER_TESTING_BankConfiguration bc; * @param label label to use for the command. */ #define CMD_EXEC_AGGREGATOR(label) \ - TALER_TESTING_cmd_exec_aggregator (label "-aggregator", CONFIG_FILE), \ - TALER_TESTING_cmd_exec_transfer (label "-transfer", CONFIG_FILE) + TALER_TESTING_cmd_exec_aggregator (label "-aggregator", config_file), \ + TALER_TESTING_cmd_exec_transfer (label "-transfer", config_file) /** @@ -144,6 +155,11 @@ run (void *cls, /** * Withdraw EUR:1 using the SAME private coin key as for the previous coin * (in violation of the specification, to be detected on spending!). + * However, note that this does NOT work with 'CS', as for a different + * denomination we get different R0/R1 values from the exchange, and + * thus will generate a different coin private key as R0/R1 are hashed + * into the coin priv. So here, we fail to 'reuse' the key due to the + * cryptographic construction! */ TALER_TESTING_cmd_withdraw_amount_reuse_key ("withdraw-coin-1x", "create-reserve-1", @@ -184,6 +200,13 @@ run (void *cls, TALER_TESTING_cmd_deposit_replay ("deposit-simple-replay", "deposit-simple", MHD_HTTP_OK), + /* This creates a conflict, as we have the same coin public key (reuse!), + but different denomination public keys (which is not allowed). + However, note that this does NOT work with 'CS', as for a different + denomination we get different R0/R1 values from the exchange, and + thus will generate a different coin private key as R0/R1 are hashed + into the coin priv. So here, we fail to 'reuse' the key due to the + cryptographic construction! */ TALER_TESTING_cmd_deposit ("deposit-reused-coin-key-failure", "withdraw-coin-1x", 0, @@ -191,7 +214,9 @@ run (void *cls, "{\"items\":[{\"name\":\"ice cream\",\"value\":1}]}", GNUNET_TIME_UNIT_ZERO, "EUR:1", - MHD_HTTP_CONFLICT), + uses_cs + ? MHD_HTTP_OK + : MHD_HTTP_CONFLICT), /** * Try to double spend using different wire details. */ @@ -234,7 +259,10 @@ run (void *cls, struct TALER_TESTING_Command refresh[] = { /** * Try to melt the coin that shared the private key with another - * coin (should fail). */ + * coin (should fail). Note that in the CS-case, we fail also + * with MHD_HTTP_CONFLICT, but for a different reason: here it + * is not a denomination conflict, but a double-spending conflict. + */ TALER_TESTING_cmd_melt ("refresh-melt-reused-coin-key-failure", "withdraw-coin-1x", MHD_HTTP_CONFLICT, @@ -452,6 +480,16 @@ run (void *cls, "EUR:0.08", bc.exchange_payto, bc.user43_payto), + /* In case of CS, one transaction above succeeded that + failed for RSA, hence we need to check for an extra transfer here */ + uses_cs + ? TALER_TESTING_cmd_check_bank_transfer ("check_bank_transfer-98c", + ec.exchange_url, + "EUR:0.98", + bc.exchange_payto, + bc.user42_payto) + : TALER_TESTING_cmd_sleep ("dummy", + 0), TALER_TESTING_cmd_check_bank_empty ("check_bank_empty"), TALER_TESTING_cmd_track_transaction ("deposit-wtid-ok", "deposit-simple", @@ -471,7 +509,6 @@ run (void *cls, TALER_TESTING_cmd_end () }; - /** * This block checks whether a wire deadline * very far in the future does NOT get aggregated now. @@ -751,7 +788,7 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-0-EUR:5", MHD_HTTP_OK, "recoup-withdraw-coin-1", - CONFIG_FILE), + config_file), /* Recoup coin to reserve */ TALER_TESTING_cmd_recoup ("recoup-1", MHD_HTTP_OK, @@ -853,14 +890,14 @@ run (void *cls, bc.exchange_payto, "short-lived-reserve"), TALER_TESTING_cmd_exec_wirewatch ("short-lived-aggregation", - CONFIG_FILE_EXPIRE_RESERVE_NOW), + config_file_expire_reserve_now), TALER_TESTING_cmd_exec_closer ("close-reserves", - CONFIG_FILE_EXPIRE_RESERVE_NOW, + config_file_expire_reserve_now, "EUR:5", "EUR:0.01", "short-lived-reserve"), TALER_TESTING_cmd_exec_transfer ("close-reserves-transfer", - CONFIG_FILE_EXPIRE_RESERVE_NOW), + config_file_expire_reserve_now), TALER_TESTING_cmd_status ("short-lived-status", "short-lived-reserve", @@ -913,8 +950,10 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-1-EUR:1", MHD_HTTP_OK, "recoup-withdraw-coin-2a", - CONFIG_FILE), - /* Check recoup is failing for the coin with the reused coin key */ + config_file), + /* Check recoup is failing for the coin with the reused coin key + (fails either because of denomination conflict (RSA) or + double-spending (CS))*/ TALER_TESTING_cmd_recoup ("recoup-2x", MHD_HTTP_CONFLICT, "withdraw-coin-1x", @@ -986,10 +1025,10 @@ run (void *cls, "EUR:20"); reserve_open_close[(i * RESERVE_OPEN_CLOSE_CHUNK) + 1] = TALER_TESTING_cmd_exec_wirewatch ("reserve-open-close-wirewatch", - CONFIG_FILE_EXPIRE_RESERVE_NOW); + config_file_expire_reserve_now); reserve_open_close[(i * RESERVE_OPEN_CLOSE_CHUNK) + 2] = TALER_TESTING_cmd_exec_closer ("reserve-open-close-aggregation", - CONFIG_FILE_EXPIRE_RESERVE_NOW, + config_file_expire_reserve_now, "EUR:19.99", "EUR:0.01", "reserve-open-close-key"); @@ -1015,9 +1054,9 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_exec_offline_sign_fees ("offline-sign-fees", - CONFIG_FILE, + config_file, "EUR:0.01", "EUR:0.01"), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", @@ -1061,28 +1100,40 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-api", + GNUNET_log_setup (argv[0], "INFO", NULL); TALER_extensions_init (); + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + uses_cs = (0 == strcmp (cipher, "cs")); + GNUNET_asprintf (&config_file, + "test_exchange_api-%s.conf", + cipher); + GNUNET_asprintf (&config_file_expire_reserve_now, + "test_exchange_api_expire_reserve_now-%s.conf", + cipher); + GNUNET_free (cipher); + /* Check fakebank port is available and get config */ if (GNUNET_OK != - TALER_TESTING_prepare_fakebank (CONFIG_FILE, + TALER_TESTING_prepare_fakebank (config_file, "exchange-account-2", &bc)) return 77; - TALER_TESTING_cleanup_files (CONFIG_FILE); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Run keyup, create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -1099,7 +1150,7 @@ main (int argc, */ TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE)) + config_file)) return 2; break; default: diff --git a/src/testing/test_exchange_api_expire_reserve_now-cs.conf b/src/testing/test_exchange_api_expire_reserve_now-cs.conf new file mode 100644 index 000000000..2cc4e0917 --- /dev/null +++ b/src/testing/test_exchange_api_expire_reserve_now-cs.conf @@ -0,0 +1,4 @@ +@INLINE@ test_exchange_api-cs.conf + +[exchangedb] +IDLE_RESERVE_EXPIRATION_TIME = 0 s diff --git a/src/testing/test_exchange_api_expire_reserve_now-rsa.conf b/src/testing/test_exchange_api_expire_reserve_now-rsa.conf new file mode 100644 index 000000000..52b829871 --- /dev/null +++ b/src/testing/test_exchange_api_expire_reserve_now-rsa.conf @@ -0,0 +1,4 @@ +@INLINE@ test_exchange_api-rsa.conf + +[exchangedb] +IDLE_RESERVE_EXPIRATION_TIME = 0 s diff --git a/src/testing/test_exchange_api_keys_cherry_picking-cs.conf b/src/testing/test_exchange_api_keys_cherry_picking-cs.conf new file mode 100644 index 000000000..8967d6c0a --- /dev/null +++ b/src/testing/test_exchange_api_keys_cherry_picking-cs.conf @@ -0,0 +1,98 @@ +# This file is in the public domain. +# +[PATHS] +# Persistent data storage for the testcase +TALER_TEST_HOME = test_exchange_api_keys_cherry_picking_home/ +TALER_RUNTIME_DIR = ${TMPDIR:-${TMP:-/tmp}}/${USER:-}/taler-system-runtime/ + +# Persistent data storage +TALER_DATA_HOME = $TALER_HOME/.local/share/taler/ + +# Configuration files +TALER_CONFIG_HOME = $TALER_HOME/.config/taler/ + +# Cached data, no big deal if lost +TALER_CACHE_HOME = $TALER_HOME/.cache/taler/ + +[taler] +# Currency supported by the exchange (can only be one) +CURRENCY = EUR + +[taler-exchange-secmod-cs] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days + +[taler-exchange-secmod-eddsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days +# Reduce from 12 weeks to ensure we have multiple +DURATION = 14 days + +[auditor] +BASE_URL = "http://localhost:8083/" + +# HTTP port the auditor listens to +PORT = 8083 + +[exchange] +# HTTP port the exchange listens to +PORT = 8081 + +# Master public key used to sign the exchange's various keys +MASTER_PUBLIC_KEY = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG + +# How to access our database +DB = postgres + +# Base URL of the exchange. Must be set to a URL where the +# exchange (or the twister) is actually listening. +BASE_URL = "http://localhost:8081/" + + +[exchangedb-postgres] +CONFIG = "postgres:///talercheck" + +[auditordb-postgres] +CONFIG = "postgres:///talercheck" + +[exchange-account-1] +PAYTO_URI = payto://x-taler-bank/localhost/42 + +[exchange-accountcredentials-1] +WIRE_GATEWAY_URL = "http://localhost:9082/42/" + +[exchange-account-2] +PAYTO_URI = payto://x-taler-bank/localhost/2 +ENABLE_DEBIT = YES +ENABLE_CREDIT = YES + +[exchange-accountcredentials-2] +WIRE_GATEWAY_URL = "http://localhost:9082/2/" + +# Authentication information for basic authentication +TALER_BANK_AUTH_METHOD = "basic" +USERNAME = user +PASSWORD = pass + +[bank] +HTTP_PORT=8082 + +[taler-exchange-secmod-cs] +OVERLAP_DURATION = 1 s +LOOKAHEAD_SIGN = 20 s + +[taler-exchange-secmod-eddsa] +OVERLAP_DURATION = 1 s +DURATION = 30 s +LOOKAHEAD_SIGN = 20 s + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 5 s +duration_spend = 6 s +duration_legal = 7 s +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/testing/test_exchange_api_keys_cherry_picking.conf b/src/testing/test_exchange_api_keys_cherry_picking-rsa.conf similarity index 99% rename from src/testing/test_exchange_api_keys_cherry_picking.conf rename to src/testing/test_exchange_api_keys_cherry_picking-rsa.conf index d7dd95352..e616738f0 100644 --- a/src/testing/test_exchange_api_keys_cherry_picking.conf +++ b/src/testing/test_exchange_api_keys_cherry_picking-rsa.conf @@ -95,4 +95,5 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 diff --git a/src/testing/test_exchange_api_keys_cherry_picking.c b/src/testing/test_exchange_api_keys_cherry_picking.c index 6ab17c634..63114c60c 100644 --- a/src/testing/test_exchange_api_keys_cherry_picking.c +++ b/src/testing/test_exchange_api_keys_cherry_picking.c @@ -29,6 +29,7 @@ lished #include "taler_exchange_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -39,7 +40,7 @@ lished * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api_keys_cherry_picking.conf" +static char *config_file; /** * Exchange configuration data. @@ -66,11 +67,11 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_fees ("offline-sign-fees", - CONFIG_FILE, + config_file, "EUR:0.01", "EUR:0.01"), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("initial-/keys", 1), TALER_TESTING_cmd_sleep ("sleep", @@ -109,19 +110,26 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-api-cherry-picking", + GNUNET_log_setup (argv[0], "DEBUG", NULL); - TALER_TESTING_cleanup_files (CONFIG_FILE); + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_exchange_api_keys_cherry_picking-%s.conf", + cipher); + GNUNET_free (cipher); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Run keyup, create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -138,7 +146,7 @@ main (int argc, */ TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE)) + config_file)) return 1; break; default: diff --git a/src/testing/test_exchange_api_overlapping_keys_bug.c b/src/testing/test_exchange_api_overlapping_keys_bug.c index 1f8c2919a..54c552236 100644 --- a/src/testing/test_exchange_api_overlapping_keys_bug.c +++ b/src/testing/test_exchange_api_overlapping_keys_bug.c @@ -31,6 +31,7 @@ #include "taler_exchange_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -40,7 +41,7 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api_keys_cherry_picking.conf" +static char *config_file; /** * Exchange configuration data. @@ -67,7 +68,7 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", 1), TALER_TESTING_cmd_check_keys ("first-download", @@ -89,18 +90,26 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-api-overlapping-keys-bug", - "DEBUG", NULL); - TALER_TESTING_cleanup_files (CONFIG_FILE); + GNUNET_log_setup (argv[0], + "DEBUG", + NULL); + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_exchange_api_keys_cherry_picking-%s.conf", + cipher); + GNUNET_free (cipher); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Run keyup, create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -117,7 +126,7 @@ main (int argc, */ TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE)) + config_file)) return 1; break; default: diff --git a/src/testing/test_exchange_api_revocation.c b/src/testing/test_exchange_api_revocation.c index 2ab72a8db..bb3dcc06e 100644 --- a/src/testing/test_exchange_api_revocation.c +++ b/src/testing/test_exchange_api_revocation.c @@ -29,6 +29,7 @@ #include "taler_exchange_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -38,7 +39,7 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api.conf" +static char *config_file; /** * Exchange configuration data. @@ -70,7 +71,7 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", 1), /** @@ -90,7 +91,7 @@ run (void *cls, * Run wire-watch to trigger the reserve creation. */ TALER_TESTING_cmd_exec_wirewatch ("wirewatch-4", - CONFIG_FILE), + config_file), /* Withdraw a 5 EUR coin, at fee of 1 ct */ TALER_TESTING_cmd_withdraw_amount ("withdraw-revocation-coin-1", "create-reserve-1", @@ -146,12 +147,12 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-2-EUR:5", MHD_HTTP_OK, "refresh-melt-1", - CONFIG_FILE), + config_file), /* Also make fully spent coin invalid (should be same denom) */ TALER_TESTING_cmd_revoke ("revoke-2-EUR:5", MHD_HTTP_OK, "withdraw-revocation-coin-2", - CONFIG_FILE), + config_file), /* Refund fully spent coin (which should fail) */ TALER_TESTING_cmd_recoup ("recoup-fully-spent", MHD_HTTP_CONFLICT, @@ -213,12 +214,12 @@ run (void *cls, TALER_TESTING_cmd_revoke ("revoke-3-EUR:0.1", MHD_HTTP_OK, "refresh-reveal-2", - CONFIG_FILE), + config_file), /* Revoke also original coin denomination */ TALER_TESTING_cmd_revoke ("revoke-4-EUR:5", MHD_HTTP_OK, "withdraw-revocation-coin-1", - CONFIG_FILE), + config_file), /* Refund coin EUR:0.1 to original coin, creating zombie! */ TALER_TESTING_cmd_recoup_refresh ("recoup-2", MHD_HTTP_OK, @@ -250,25 +251,32 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-api-revocation", + GNUNET_log_setup (argv[0], "INFO", NULL); + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_exchange_api-%s.conf", + cipher); + GNUNET_free (cipher); /* Check fakebank port is available and get config */ if (GNUNET_OK != - TALER_TESTING_prepare_fakebank (CONFIG_FILE, + TALER_TESTING_prepare_fakebank (config_file, "exchange-account-2", &bc)) return 77; - TALER_TESTING_cleanup_files (CONFIG_FILE); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Run keyup, create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -285,7 +293,7 @@ main (int argc, */ TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE)) + config_file)) return 1; break; default: diff --git a/src/testing/test_exchange_api_twisted-cs.conf b/src/testing/test_exchange_api_twisted-cs.conf new file mode 100644 index 000000000..7d2afb9cb --- /dev/null +++ b/src/testing/test_exchange_api_twisted-cs.conf @@ -0,0 +1,150 @@ +# This file is in the public domain. +[PATHS] +# Persistent data storage for the testcase +TALER_TEST_HOME = test_exchange_api_home/ +TALER_RUNTIME_DIR = ${TMPDIR:-${TMP:-/tmp}}/${USER:-}/taler-system-runtime/ + +[taler-exchange-secmod-rsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days + +[taler-exchange-secmod-eddsa] +# Reduce from 1 year to speed up test +LOOKAHEAD_SIGN = 24 days +# Reduce from 12 weeks to ensure we have multiple +DURATION = 14 days + +[taler] +# Currency supported by the exchange (can only be one) +CURRENCY = EUR +CURRENCY_ROUND_UNIT = EUR:0.01 + +[exchange] +# HTTP port the exchange listens to +PORT = 8081 + +# Master public key used to sign the exchange's various keys +MASTER_PUBLIC_KEY = 98NJW3CQHZQGQXTY3K85K531XKPAPAVV4Q5V8PYYRR00NJGZWNVG + +# How to access our database +DB = postgres + +# Base URL of the exchange ('S PROXY). This URL is where the +# twister listens at, so that it will be able to get all the +# connection addressed to the exchange. In fact, the presence +# of the twister is 100% transparent to the test case, as it +# only seeks the exchange/BASE_URL URL to connect to the exchange. +BASE_URL = "http://localhost:8888/" + +[exchangedb-postgres] +CONFIG = "postgres:///talercheck" + +[auditor] +BASE_URL = "http://localhost:8083/" +PORT = 8083 + +[auditordb-postgres] +CONFIG = "postgres:///talercheck" + +[exchange-account-1] +# What is the URL of our account? +PAYTO_URI = "payto://x-taler-bank/localhost/42" + +[exchange-accountcredentials-1] +WIRE_GATEWAY_URL = "http://localhost:9081/42/" +WIRE_GATEWAY_AUTH_METHOD = NONE + +[exchange-account-2] +PAYTO_URI = payto://x-taler-bank/localhost/2 +ENABLE_DEBIT = YES +ENABLE_CREDIT = YES + +[exchange-accountcredentials-2] +WIRE_GATEWAY_URL = "http://localhost:8082/2/" +WIRE_GATEWAY_AUTH_METHOD = BASIC +USERNAME = user +PASSWORD = pass + +[bank] +HTTP_PORT = 8082 + +[twister] +# HTTP listen port for twister +HTTP_PORT = 8888 +SERVE = tcp + +# HTTP Destination for twister. The test-Webserver needs +# to listen on the port used here. Note: no trailing '/'! +DESTINATION_BASE_URL = "http://localhost:8081" + +# Control port for TCP +# PORT = 8889 +HOSTNAME = localhost +ACCEPT_FROM = 127.0.0.1; +ACCEPT_FROM6 = ::1; + +# Control port for UNIX +UNIXPATH = /tmp/taler-service-twister.sock +UNIX_MATCH_UID = NO +UNIX_MATCH_GID = YES + +# Launching of twister by ARM +# BINARY = taler-service-twister +# AUTOSTART = NO +# FORCESTART = NO + + +[coin_eur_ct_1] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_ct_10] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_1] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_5] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + +[coin_eur_10] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS diff --git a/src/testing/test_exchange_api_twisted.conf b/src/testing/test_exchange_api_twisted-rsa.conf similarity index 98% rename from src/testing/test_exchange_api_twisted.conf rename to src/testing/test_exchange_api_twisted-rsa.conf index a41cfd43c..077d49c16 100644 --- a/src/testing/test_exchange_api_twisted.conf +++ b/src/testing/test_exchange_api_twisted-rsa.conf @@ -104,6 +104,8 @@ fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 rsa_keysize = 1024 +CIPHER = RSA + [coin_eur_ct_10] value = EUR:0.10 @@ -115,6 +117,7 @@ fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 +CIPHER = RSA [coin_eur_1] value = EUR:1 @@ -126,6 +129,7 @@ fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 +CIPHER = RSA [coin_eur_5] value = EUR:5 @@ -137,6 +141,7 @@ fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 +CIPHER = RSA [coin_eur_10] value = EUR:10 @@ -148,3 +153,4 @@ fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 rsa_keysize = 1024 +CIPHER = RSA diff --git a/src/testing/test_exchange_api_twisted.c b/src/testing/test_exchange_api_twisted.c index 02471eb91..33631764c 100644 --- a/src/testing/test_exchange_api_twisted.c +++ b/src/testing/test_exchange_api_twisted.c @@ -29,6 +29,7 @@ #include "taler_exchange_service.h" #include "taler_json_lib.h" #include +#include #include #include "taler_bank_service.h" #include "taler_fakebank_lib.h" @@ -40,7 +41,7 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api_twisted.conf" +static char *config_file; /** * (real) Twister URL. Used at startup time to check if it runs. @@ -73,7 +74,7 @@ static struct TALER_TESTING_Command CMD_EXEC_WIREWATCH (const char *label) { return TALER_TESTING_cmd_exec_wirewatch (label, - CONFIG_FILE); + config_file); } @@ -142,7 +143,7 @@ run (void *cls, NULL), /* Trigger 409 Conflict. */ TALER_TESTING_cmd_flip_upload ("flip-upload", - CONFIG_FILE, + config_file, "transfer_privs.0"), TALER_TESTING_cmd_refresh_reveal ("refresh-(flipped-)reveal", "refresh-melt", @@ -178,7 +179,7 @@ run (void *cls, "USD:5", "deposit-refund-1"), TALER_TESTING_cmd_flip_upload ("flip-upload", - CONFIG_FILE, + config_file, "merchant_sig"), TALER_TESTING_cmd_refund ("refund-bad-sig", MHD_HTTP_FORBIDDEN, @@ -217,7 +218,7 @@ run (void *cls, */ struct TALER_TESTING_Command expired_keys[] = { TALER_TESTING_cmd_modify_header_dl ("modify-expiration", - CONFIG_FILE, + config_file, MHD_HTTP_HEADER_EXPIRES, "Wed, 19 Jan 586524 08:01:49 GMT"), TALER_TESTING_cmd_check_keys_pull_all_keys ( @@ -243,7 +244,7 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("offline-sign-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", 1), TALER_TESTING_cmd_batch ("refresh-reveal-409-conflict", @@ -283,26 +284,32 @@ int main (int argc, char *const *argv) { + char *cipher; int ret; (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-api-twisted", + GNUNET_log_setup (argv[0], "DEBUG", NULL); + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_exchange_api_twisted-%s.conf", + cipher); + GNUNET_free (cipher); if (GNUNET_OK != - TALER_TESTING_prepare_fakebank (CONFIG_FILE, + TALER_TESTING_prepare_fakebank (config_file, "exchange-account-2", &bc)) return 77; if (NULL == (twister_url = TALER_TWISTER_prepare_twister - (CONFIG_FILE))) + (config_file))) return 77; - TALER_TESTING_cleanup_files (CONFIG_FILE); - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + TALER_TESTING_cleanup_files (config_file); + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, &ec)) { @@ -312,11 +319,11 @@ main (int argc, case GNUNET_NO: return 77; case GNUNET_OK: - if (NULL == (twisterd = TALER_TWISTER_run_twister (CONFIG_FILE))) + if (NULL == (twisterd = TALER_TWISTER_run_twister (config_file))) return 77; ret = TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE); + config_file); purge_process (twisterd); GNUNET_free (twister_url); diff --git a/src/testing/test_exchange_management_api.c b/src/testing/test_exchange_management_api.c index b2d7871ea..71251a57f 100644 --- a/src/testing/test_exchange_management_api.c +++ b/src/testing/test_exchange_management_api.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2020 Taler Systems SA + Copyright (C) 2020-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as @@ -25,6 +25,7 @@ #include "taler_util.h" #include "taler_exchange_service.h" #include +#include #include #include "taler_testing_lib.h" @@ -32,7 +33,7 @@ * Configuration file we use. One (big) configuration is used * for the various components for this test. */ -#define CONFIG_FILE "test_exchange_api.conf" +static char *config_file; /** @@ -139,7 +140,7 @@ run (void *cls, MHD_HTTP_NO_CONTENT, false), TALER_TESTING_cmd_exec_offline_sign_keys ("download-future-keys", - CONFIG_FILE), + config_file), TALER_TESTING_cmd_check_keys_pull_all_keys ("refetch /keys", 1), TALER_TESTING_cmd_end () @@ -156,25 +157,32 @@ int main (int argc, char *const *argv) { + char *cipher; + (void) argc; - (void) argv; /* These environment variables get in the way... */ unsetenv ("XDG_DATA_HOME"); unsetenv ("XDG_CONFIG_HOME"); - GNUNET_log_setup ("test-exchange-management-api", + GNUNET_log_setup (argv[0], "INFO", NULL); /* Check fakebank port is available and get config */ + cipher = GNUNET_TESTING_get_testname_from_underscore (argv[0]); + GNUNET_assert (NULL != cipher); + GNUNET_asprintf (&config_file, + "test_exchange_api-%s.conf", + cipher); + GNUNET_free (cipher); if (GNUNET_OK != - TALER_TESTING_prepare_fakebank (CONFIG_FILE, + TALER_TESTING_prepare_fakebank (config_file, "exchange-account-2", &bc)) return 77; - TALER_TESTING_cleanup_files (CONFIG_FILE); + TALER_TESTING_cleanup_files (config_file); /* @helpers. Create tables, ... Note: it * fetches the port number from config in order to see * if it's available. */ - switch (TALER_TESTING_prepare_exchange (CONFIG_FILE, + switch (TALER_TESTING_prepare_exchange (config_file, GNUNET_YES, /* reset DB? */ &ec)) { @@ -191,7 +199,7 @@ main (int argc, */ TALER_TESTING_setup_with_exchange (&run, NULL, - CONFIG_FILE)) + config_file)) return 1; break; default: diff --git a/src/testing/test_kyc_api.conf b/src/testing/test_kyc_api.conf index 8ca6b74b8..2dce408b4 100644 --- a/src/testing/test_kyc_api.conf +++ b/src/testing/test_kyc_api.conf @@ -110,8 +110,20 @@ fee_withdraw = EUR:0.00 fee_deposit = EUR:0.00 fee_refresh = EUR:0.01 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 +[coin_eur_ct_2] +value = EUR:0.01 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.00 +fee_deposit = EUR:0.00 +fee_refresh = EUR:0.01 +fee_refund = EUR:0.01 +CIPHER = CS + [coin_eur_ct_10] value = EUR:0.10 duration_withdraw = 7 days @@ -121,8 +133,20 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 +[coin_eur_ct_11] +value = EUR:0.10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + [coin_eur_1] value = EUR:1 duration_withdraw = 7 days @@ -132,8 +156,20 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 +[coin_eur_2] +value = EUR:1 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + [coin_eur_5] value = EUR:5 duration_withdraw = 7 days @@ -143,8 +179,20 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 +[coin_eur_6] +value = EUR:5 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS + [coin_eur_10] value = EUR:10 duration_withdraw = 7 days @@ -154,4 +202,16 @@ fee_withdraw = EUR:0.01 fee_deposit = EUR:0.01 fee_refresh = EUR:0.03 fee_refund = EUR:0.01 +CIPHER = RSA rsa_keysize = 1024 + +[coin_eur_11] +value = EUR:10 +duration_withdraw = 7 days +duration_spend = 2 years +duration_legal = 3 years +fee_withdraw = EUR:0.01 +fee_deposit = EUR:0.01 +fee_refresh = EUR:0.03 +fee_refund = EUR:0.01 +CIPHER = CS \ No newline at end of file diff --git a/src/testing/testing_api_cmd_bank_check.c b/src/testing/testing_api_cmd_bank_check.c index ed4cde461..be4ad3189 100644 --- a/src/testing/testing_api_cmd_bank_check.c +++ b/src/testing/testing_api_cmd_bank_check.c @@ -228,19 +228,6 @@ check_bank_transfer_traits (void *cls, } -/** - * Make a "bank check" CMD. It checks whether a - * particular wire transfer has been made or not. - * - * @param label the command label. - * @param exchange_base_url base url of the exchange involved in - * the wire transfer. - * @param amount the amount expected to be transferred. - * @param debit_payto the account that gave money. - * @param credit_payto the account that received money. - * - * @return the command - */ struct TALER_TESTING_Command TALER_TESTING_cmd_check_bank_transfer (const char *label, const char *exchange_base_url, @@ -270,19 +257,9 @@ TALER_TESTING_cmd_check_bank_transfer (const char *label, } -/** - * Define a "bank check" CMD that takes the input - * data from another CMD that offers it. - * - * @param label command label. - * @param deposit_reference reference to a CMD that is - * able to provide the "check bank transfer" operation - * input data. - * @return the command. - */ struct TALER_TESTING_Command -TALER_TESTING_cmd_check_bank_transfer_with_ref - (const char *label, +TALER_TESTING_cmd_check_bank_transfer_with_ref ( + const char *label, const char *deposit_reference) { struct BankCheckState *bcs; diff --git a/src/testing/testing_api_cmd_deposit.c b/src/testing/testing_api_cmd_deposit.c index 67c2c7021..d3fafc630 100644 --- a/src/testing/testing_api_cmd_deposit.c +++ b/src/testing/testing_api_cmd_deposit.c @@ -295,7 +295,7 @@ deposit_run (void *cls, struct TALER_MerchantPublicKeyP merchant_pub; struct TALER_PrivateContractHash h_contract_terms; enum TALER_ErrorCode ec; - struct TALER_WireSalt wire_salt; + struct TALER_WireSaltP wire_salt; const char *payto_uri; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_string ("payto_uri", diff --git a/src/testing/testing_api_cmd_insert_deposit.c b/src/testing/testing_api_cmd_insert_deposit.c index 4e3ce2147..dcda7cf33 100644 --- a/src/testing/testing_api_cmd_insert_deposit.c +++ b/src/testing/testing_api_cmd_insert_deposit.c @@ -201,27 +201,33 @@ insert_deposit_run (void *cls, struct TALER_CoinPubHash c_hash; struct TALER_PlanchetDetail pd; struct TALER_BlindedDenominationSignature bds; + struct TALER_PlanchetMasterSecretP ps; + struct TALER_ExchangeWithdrawValues alg_values; union TALER_DenominationBlindingKeyP bks; - TALER_blinding_secret_create (&bks); + alg_values.cipher = TALER_DENOMINATION_RSA; + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); GNUNET_assert (GNUNET_OK == TALER_denom_blind (&dpk, &bks, NULL, /* FIXME-Oec */ &deposit.coin.coin_pub, + &alg_values, &c_hash, - &pd.coin_ev, - &pd.coin_ev_size)); + &pd.blinded_planchet)); GNUNET_assert (GNUNET_OK == TALER_denom_sign_blinded (&bds, &denom_priv, - pd.coin_ev, - pd.coin_ev_size)); - GNUNET_free (pd.coin_ev); + &pd.blinded_planchet)); + TALER_blinded_planchet_free (&pd.blinded_planchet); GNUNET_assert (GNUNET_OK == TALER_denom_sig_unblind (&deposit.coin.denom_sig, &bds, &bks, + &c_hash, + &alg_values, &dpk)); TALER_blinded_denom_sig_free (&bds); } diff --git a/src/testing/testing_api_cmd_oauth.c b/src/testing/testing_api_cmd_oauth.c index eaf7f9068..045b5eefa 100644 --- a/src/testing/testing_api_cmd_oauth.c +++ b/src/testing/testing_api_cmd_oauth.c @@ -131,16 +131,17 @@ handle_post (void *cls, * * @param cls argument given together with the function * pointer when the handler was registered with MHD + * @param connection the connection being handled * @param url the requested url * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @param version the HTTP version string (i.e. - * #MHD_HTTP_VERSION_1_1) + * MHD_HTTP_VERSION_1_1) * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as - * part of #MHD_get_connection_values; very large POST + * part of MHD_get_connection_values(); very large POST * data *will* be made available incrementally in * @a upload_data) * @param[in,out] upload_data_size set initially to the size of the @@ -153,7 +154,7 @@ handle_post (void *cls, * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the - * global #MHD_RequestCompletedCallback (which + * global MHD_RequestCompletedCallback (which * can be set with the #MHD_OPTION_NOTIFY_COMPLETED). * Initially, `*con_cls` will be NULL. * @return #MHD_YES if the connection was handled successfully, diff --git a/src/testing/testing_api_cmd_recoup.c b/src/testing/testing_api_cmd_recoup.c index 7bd477377..85256c207 100644 --- a/src/testing/testing_api_cmd_recoup.c +++ b/src/testing/testing_api_cmd_recoup.c @@ -237,12 +237,12 @@ recoup_run (void *cls, struct RecoupState *ps = cls; const struct TALER_TESTING_Command *coin_cmd; const struct TALER_CoinSpendPrivateKeyP *coin_priv; - const union TALER_DenominationBlindingKeyP *blinding_key; const struct TALER_EXCHANGE_DenomPublicKey *denom_pub; const struct TALER_DenominationSignature *coin_sig; - struct TALER_PlanchetSecretsP planchet; + const struct TALER_PlanchetMasterSecretP *planchet; char *cref; unsigned int idx; + const struct TALER_ExchangeWithdrawValues *ewv; ps->is = is; if (GNUNET_OK != @@ -264,7 +264,6 @@ recoup_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - if (GNUNET_OK != TALER_TESTING_get_trait_coin_priv (coin_cmd, idx, @@ -274,18 +273,23 @@ recoup_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - if (GNUNET_OK != - TALER_TESTING_get_trait_blinding_key (coin_cmd, - idx, - &blinding_key)) + TALER_TESTING_get_trait_exchange_wd_value (coin_cmd, + idx, + &ewv)) + { + GNUNET_break (0); + TALER_TESTING_interpreter_fail (is); + return; + } + if (GNUNET_OK != + TALER_TESTING_get_trait_planchet_secret (coin_cmd, + &planchet)) { GNUNET_break (0); TALER_TESTING_interpreter_fail (is); return; } - planchet.coin_priv = *coin_priv; - planchet.blinding_key = *blinding_key; GNUNET_CRYPTO_eddsa_key_get_public ( &coin_priv->eddsa_priv, &ps->reserve_history.details.recoup_details.coin_pub.eddsa_pub); @@ -299,7 +303,6 @@ recoup_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - if (GNUNET_OK != TALER_TESTING_get_trait_denom_sig (coin_cmd, idx, @@ -309,15 +312,14 @@ recoup_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Trying to recoup denomination '%s'\n", TALER_B2S (&denom_pub->h_key)); - ps->ph = TALER_EXCHANGE_recoup (is->exchange, denom_pub, coin_sig, - &planchet, + ewv, + planchet, &recoup_cb, ps); GNUNET_assert (NULL != ps->ph); diff --git a/src/testing/testing_api_cmd_recoup_refresh.c b/src/testing/testing_api_cmd_recoup_refresh.c index 9287cdf30..1102fc757 100644 --- a/src/testing/testing_api_cmd_recoup_refresh.c +++ b/src/testing/testing_api_cmd_recoup_refresh.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2018 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as @@ -125,14 +125,14 @@ recoup_refresh_cb (void *cls, const struct TALER_EXCHANGE_HttpResponse *hr, const struct TALER_CoinSpendPublicKeyP *old_coin_pub) { - struct RecoupRefreshState *ps = cls; - struct TALER_TESTING_Interpreter *is = ps->is; + struct RecoupRefreshState *rrs = cls; + struct TALER_TESTING_Interpreter *is = rrs->is; struct TALER_TESTING_Command *cmd = &is->commands[is->ip]; char *cref; unsigned int idx; - ps->ph = NULL; - if (ps->expected_response_code != hr->http_status) + rrs->ph = NULL; + if (rrs->expected_response_code != hr->http_status) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected response code %u/%d to command %s in %s:%u\n", @@ -150,7 +150,7 @@ recoup_refresh_cb (void *cls, } if (GNUNET_OK != - parse_coin_reference (ps->coin_reference, + parse_coin_reference (rrs->coin_reference, &cref, &idx)) { @@ -170,7 +170,7 @@ recoup_refresh_cb (void *cls, struct TALER_CoinSpendPublicKeyP oc; melt_cmd = TALER_TESTING_interpreter_lookup_command (is, - ps->melt_reference); + rrs->melt_reference); if (NULL == melt_cmd) { GNUNET_break (0); @@ -185,7 +185,7 @@ recoup_refresh_cb (void *cls, GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Coin %u not found in command %s\n", 0, - ps->melt_reference); + rrs->melt_reference); GNUNET_break (0); TALER_TESTING_interpreter_fail (is); return; @@ -228,19 +228,21 @@ recoup_refresh_run (void *cls, const struct TALER_TESTING_Command *cmd, struct TALER_TESTING_Interpreter *is) { - struct RecoupRefreshState *ps = cls; + struct RecoupRefreshState *rrs = cls; const struct TALER_TESTING_Command *coin_cmd; + const struct TALER_TESTING_Command *melt_cmd; const struct TALER_CoinSpendPrivateKeyP *coin_priv; - const union TALER_DenominationBlindingKeyP *blinding_key; const struct TALER_EXCHANGE_DenomPublicKey *denom_pub; const struct TALER_DenominationSignature *coin_sig; - struct TALER_PlanchetSecretsP planchet; + const struct TALER_RefreshMasterSecretP *rplanchet; + const struct TALER_PlanchetMasterSecretP *planchet; + const struct TALER_ExchangeWithdrawValues *ewv; char *cref; unsigned int idx; - ps->is = is; + rrs->is = is; if (GNUNET_OK != - parse_coin_reference (ps->coin_reference, + parse_coin_reference (rrs->coin_reference, &cref, &idx)) { @@ -251,14 +253,20 @@ recoup_refresh_run (void *cls, coin_cmd = TALER_TESTING_interpreter_lookup_command (is, cref); GNUNET_free (cref); - if (NULL == coin_cmd) { GNUNET_break (0); TALER_TESTING_interpreter_fail (is); return; } - + melt_cmd = TALER_TESTING_interpreter_lookup_command (is, + rrs->melt_reference); + if (NULL == melt_cmd) + { + GNUNET_break (0); + TALER_TESTING_interpreter_fail (is); + return; + } if (GNUNET_OK != TALER_TESTING_get_trait_coin_priv (coin_cmd, idx, @@ -268,19 +276,32 @@ recoup_refresh_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - if (GNUNET_OK != - TALER_TESTING_get_trait_blinding_key (coin_cmd, - idx, - &blinding_key)) + TALER_TESTING_get_trait_exchange_wd_value (melt_cmd, + idx, + &ewv)) + { + GNUNET_break (0); + TALER_TESTING_interpreter_fail (is); + return; + } + if (GNUNET_OK != + TALER_TESTING_get_trait_planchet_secrets (coin_cmd, + idx, + &planchet)) + { + GNUNET_break (0); + TALER_TESTING_interpreter_fail (is); + return; + } + if (GNUNET_OK != + TALER_TESTING_get_trait_refresh_secret (melt_cmd, + &rplanchet)) { GNUNET_break (0); TALER_TESTING_interpreter_fail (is); return; } - planchet.coin_priv = *coin_priv; - planchet.blinding_key = *blinding_key; - if (GNUNET_OK != TALER_TESTING_get_trait_denom_pub (coin_cmd, idx, @@ -290,7 +311,6 @@ recoup_refresh_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - if (GNUNET_OK != TALER_TESTING_get_trait_denom_sig (coin_cmd, idx, @@ -300,18 +320,19 @@ recoup_refresh_run (void *cls, TALER_TESTING_interpreter_fail (is); return; } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Trying to recoup_refresh denomination '%s'\n", TALER_B2S (&denom_pub->h_key)); - - ps->ph = TALER_EXCHANGE_recoup_refresh (is->exchange, - denom_pub, - coin_sig, - &planchet, - recoup_refresh_cb, - ps); - GNUNET_assert (NULL != ps->ph); + rrs->ph = TALER_EXCHANGE_recoup_refresh (is->exchange, + denom_pub, + coin_sig, + ewv, + rplanchet, + planchet, + idx, + &recoup_refresh_cb, + rrs); + GNUNET_assert (NULL != rrs->ph); } @@ -326,13 +347,13 @@ static void recoup_refresh_cleanup (void *cls, const struct TALER_TESTING_Command *cmd) { - struct RecoupRefreshState *ps = cls; - if (NULL != ps->ph) + struct RecoupRefreshState *rrs = cls; + if (NULL != rrs->ph) { - TALER_EXCHANGE_recoup_refresh_cancel (ps->ph); - ps->ph = NULL; + TALER_EXCHANGE_recoup_refresh_cancel (rrs->ph); + rrs->ph = NULL; } - GNUNET_free (ps); + GNUNET_free (rrs); } @@ -343,15 +364,15 @@ TALER_TESTING_cmd_recoup_refresh (const char *label, const char *melt_reference, const char *amount) { - struct RecoupRefreshState *ps; + struct RecoupRefreshState *rrs; - ps = GNUNET_new (struct RecoupRefreshState); - ps->expected_response_code = expected_response_code; - ps->coin_reference = coin_reference; - ps->melt_reference = melt_reference; + rrs = GNUNET_new (struct RecoupRefreshState); + rrs->expected_response_code = expected_response_code; + rrs->coin_reference = coin_reference; + rrs->melt_reference = melt_reference; if (GNUNET_OK != TALER_string_to_amount (amount, - &ps->amount)) + &rrs->amount)) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to parse amount `%s' at %s\n", @@ -361,7 +382,7 @@ TALER_TESTING_cmd_recoup_refresh (const char *label, } { struct TALER_TESTING_Command cmd = { - .cls = ps, + .cls = rrs, .label = label, .run = &recoup_refresh_run, .cleanup = &recoup_refresh_cleanup diff --git a/src/testing/testing_api_cmd_refresh.c b/src/testing/testing_api_cmd_refresh.c index db2537a30..11c88c19c 100644 --- a/src/testing/testing_api_cmd_refresh.c +++ b/src/testing/testing_api_cmd_refresh.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2018-2020 Taler Systems SA + Copyright (C) 2018-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -96,9 +96,9 @@ struct RefreshMeltState const char *coin_reference; /** - * "Crypto data" used in the refresh operation. + * Data used in the refresh operation. */ - json_t *refresh_data; + struct TALER_EXCHANGE_RefreshData refresh_data; /** * Reference to a previous melt command. @@ -121,6 +121,17 @@ struct RefreshMeltState */ struct TALER_EXCHANGE_DenomPublicKey *fresh_pks; + /** + * Array of @e num_fresh_coins of results from + * the melt operation. + */ + struct TALER_EXCHANGE_MeltBlindingDetail *mbds; + + /** + * Entropy seed for the refresh-melt operation. + */ + struct TALER_RefreshMasterSecretP rms; + /** * Private key of the dirty coin being melted. */ @@ -172,7 +183,7 @@ struct RefreshMeltState * exchange to pick any previous /rerfesh/melt operation from * the database. */ - unsigned int double_melt; + bool double_melt; /** * How often should we retry on (transient) failures? @@ -208,6 +219,12 @@ struct RefreshRevealState */ struct TALER_TESTING_FreshCoinData *fresh_coins; + /** + * Array of @e num_fresh_coins planchet secrets derived + * from the transfer secret per fresh coin. + */ + struct TALER_PlanchetMasterSecretP *psa; + /** * Interpreter state. */ @@ -340,17 +357,16 @@ do_reveal_retry (void *cls) * failed. * @param coin_privs array of @a num_coins private keys for the * coins that were created, NULL on error. + * @param psa array of @a num_coins planchet secrets (derived from the transfer secret) for each of the coins * @param sigs array of signature over @a num_coins coins, * NULL on error. */ static void reveal_cb (void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - unsigned int num_coins, - const struct TALER_PlanchetSecretsP *coin_privs, - const struct TALER_DenominationSignature *sigs) + const struct TALER_EXCHANGE_RevealResult *rr) { struct RefreshRevealState *rrs = cls; + const struct TALER_EXCHANGE_HttpResponse *hr = &rr->hr; const struct TALER_TESTING_Command *melt_cmd; rrs->rrh = NULL; @@ -403,16 +419,22 @@ reveal_cb (void *cls, TALER_TESTING_interpreter_fail (rrs->is); return; } - rrs->num_fresh_coins = num_coins; switch (hr->http_status) { case MHD_HTTP_OK: - rrs->fresh_coins = GNUNET_new_array (num_coins, + rrs->num_fresh_coins = rr->details.success.num_coins; + rrs->psa = GNUNET_new_array (rrs->num_fresh_coins, + struct TALER_PlanchetMasterSecretP); + rrs->fresh_coins = GNUNET_new_array (rrs->num_fresh_coins, struct TALER_TESTING_FreshCoinData); - for (unsigned int i = 0; inum_fresh_coins; i++) { + const struct TALER_EXCHANGE_RevealedCoinInfo *coin + = &rr->details.success.coins[i]; struct TALER_TESTING_FreshCoinData *fc = &rrs->fresh_coins[i]; + rrs->psa[i] = coin->ps; + fc->blinding_key = coin->bks; if (GNUNET_OK != TALER_TESTING_get_trait_denom_pub (melt_cmd, i, @@ -422,10 +444,10 @@ reveal_cb (void *cls, TALER_TESTING_interpreter_fail (rrs->is); return; } - fc->coin_priv = coin_privs[i].coin_priv; - fc->blinding_key = coin_privs[i].blinding_key; + fc->coin_priv = coin->coin_priv; + TALER_denom_sig_deep_copy (&fc->sig, - &sigs[i]); + &coin->sig); } if (0 != rrs->total_backoff.rel_value_us) { @@ -471,13 +493,22 @@ refresh_reveal_run (void *cls, TALER_TESTING_interpreter_fail (rrs->is); return; } + // FIXME: use trait for 'rms'! rms = melt_cmd->cls; - rrs->rrh = TALER_EXCHANGE_refreshes_reveal (is->exchange, - rms->refresh_data, - rms->noreveal_index, - &reveal_cb, - rrs); + { + struct TALER_ExchangeWithdrawValues alg_values[rms->num_fresh_coins]; + for (unsigned int i = 0; inum_fresh_coins; i++) + alg_values[i] = rms->mbds[i].alg_value; + rrs->rrh = TALER_EXCHANGE_refreshes_reveal (is->exchange, + &rms->rms, + &rms->refresh_data, + rms->num_fresh_coins, + alg_values, + rms->noreveal_index, + &reveal_cb, + rrs); + } if (NULL == rrs->rrh) { GNUNET_break (0); @@ -520,7 +551,7 @@ refresh_reveal_cleanup (void *cls, TALER_denom_sig_free (&rrs->fresh_coins[j].sig); GNUNET_free (rrs->fresh_coins); - rrs->fresh_coins = NULL; + GNUNET_free (rrs->psa); rrs->num_fresh_coins = 0; GNUNET_free (rrs); } @@ -577,13 +608,10 @@ do_link_retry (void *cls) */ static void link_cb (void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - unsigned int num_coins, - const struct TALER_CoinSpendPrivateKeyP *coin_privs, - const struct TALER_DenominationSignature *sigs, - const struct TALER_DenominationPublicKey *pubs) + const struct TALER_EXCHANGE_LinkResult *lr) { struct RefreshLinkState *rls = cls; + const struct TALER_EXCHANGE_HttpResponse *hr = &lr->hr; const struct TALER_TESTING_Command *reveal_cmd; struct TALER_TESTING_Command *link_cmd = &rls->is->commands[rls->is->ip]; unsigned int found; @@ -652,11 +680,11 @@ link_cb (void *cls, TALER_TESTING_interpreter_fail (rls->is); return; } - if (num_coins != *num_fresh_coins) + if (lr->details.success.num_coins != *num_fresh_coins) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected number of fresh coins: %d vs %d in %s:%u\n", - num_coins, + lr->details.success.num_coins, *num_fresh_coins, __FILE__, __LINE__); @@ -664,11 +692,11 @@ link_cb (void *cls, return; } /* check that the coins match */ - for (unsigned int i = 0; idetails.success.num_coins; i++) + for (unsigned int j = i + 1; jdetails.success.num_coins; j++) if (0 == - GNUNET_memcmp (&coin_privs[i], - &coin_privs[j])) + GNUNET_memcmp (&lr->details.success.coins[i].coin_priv, + &lr->details.success.coins[j].coin_priv)) GNUNET_break (0); /* Note: coins might be legitimately permutated in here... */ found = 0; @@ -686,29 +714,38 @@ link_cb (void *cls, return; } - for (unsigned int i = 0; idetails.success.num_coins; i++) + { + const struct TALER_EXCHANGE_LinkedCoinInfo *lci_i + = &lr->details.success.coins[i]; + + for (unsigned int j = 0; jdetails.success.num_coins; j++) { + const struct TALER_TESTING_FreshCoinData *fcj + = &(*fc)[j]; + if ( (0 == - GNUNET_memcmp (&coin_privs[i], - &(*fc)[j].coin_priv)) && + GNUNET_memcmp (&fcj->coin_priv, + &lci_i->coin_priv)) && (0 == - TALER_denom_sig_cmp (&(*fc)[i].sig, - &sigs[j])) && + TALER_denom_sig_cmp (&fcj->sig, + &lci_i->sig)) && (0 == - TALER_denom_pub_cmp (&(*fc)[i].pk->key, - &pubs[j])) ) + TALER_denom_pub_cmp (&fcj->pk->key, + &lci_i->pub)) ) { found++; break; } - } + } /* for j*/ + } /* for i */ } - if (found != num_coins) + if (found != lr->details.success.num_coins) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Only %u/%u coins match expectations\n", - found, num_coins); + found, + lr->details.success.num_coins); GNUNET_break (0); TALER_TESTING_interpreter_fail (rls->is); return; @@ -773,6 +810,7 @@ refresh_link_run (void *cls, /* find reserve_withdraw command */ { + // FIXME: use trait! rms = melt_cmd->cls; coin_cmd = TALER_TESTING_interpreter_lookup_command (rls->is, rms->coin_reference); @@ -785,8 +823,10 @@ refresh_link_run (void *cls, } const struct TALER_CoinSpendPrivateKeyP *coin_priv; - if (GNUNET_OK != TALER_TESTING_get_trait_coin_priv - (coin_cmd, 0, &coin_priv)) + if (GNUNET_OK != + TALER_TESTING_get_trait_coin_priv (coin_cmd, + 0, + &coin_priv)) { GNUNET_break (0); TALER_TESTING_interpreter_fail (rls->is); @@ -866,11 +906,6 @@ do_melt_retry (void *cls) rms->retry_task = NULL; rms->is->commands[rms->is->ip].last_req_time = GNUNET_TIME_absolute_get (); - if (NULL != rms->refresh_data) - { - json_decref (rms->refresh_data); - rms->refresh_data = NULL; - } melt_run (rms, NULL, rms->is); @@ -883,20 +918,15 @@ do_melt_retry (void *cls) * CMD was set to do so. * * @param cls closure. - * @param hr HTTP response details - * @param noreveal_index choice by the exchange in the - * cut-and-choose protocol, UINT16_MAX on error. - * @param exchange_pub public key the exchange used for signing. + * @param mr melt response details */ static void melt_cb (void *cls, - const struct TALER_EXCHANGE_HttpResponse *hr, - uint32_t noreveal_index, - const struct TALER_ExchangePublicKeyP *exchange_pub) + const struct TALER_EXCHANGE_MeltResponse *mr) { struct RefreshMeltState *rms = cls; + const struct TALER_EXCHANGE_HttpResponse *hr = &mr->hr; - (void) exchange_pub; rms->rmh = NULL; if (rms->expected_response_code != hr->http_status) { @@ -939,7 +969,21 @@ melt_cb (void *cls, TALER_TESTING_interpreter_fail (rms->is); return; } - rms->noreveal_index = noreveal_index; + if (MHD_HTTP_OK == hr->http_status) + { + rms->noreveal_index = mr->details.success.noreveal_index; + if (mr->details.success.num_mbds != rms->num_fresh_coins) + { + GNUNET_break (0); + TALER_TESTING_interpreter_fail (rms->is); + return; + } + GNUNET_free (rms->mbds); + rms->mbds = GNUNET_memdup (mr->details.success.mbds, + mr->details.success.num_mbds + * sizeof (struct + TALER_EXCHANGE_MeltBlindingDetail)); + } if (0 != rms->total_backoff.rel_value_us) { GNUNET_log (GNUNET_ERROR_TYPE_INFO, @@ -948,15 +992,16 @@ melt_cb (void *cls, GNUNET_STRINGS_relative_time_to_string (rms->total_backoff, GNUNET_YES)); } - if (GNUNET_YES == rms->double_melt) + if (rms->double_melt) { TALER_LOG_DEBUG ("Doubling the melt (%s)\n", rms->is->commands[rms->is->ip].label); rms->rmh = TALER_EXCHANGE_melt (rms->is->exchange, - rms->refresh_data, + &rms->rms, + &rms->refresh_data, &melt_cb, rms); - rms->double_melt = GNUNET_NO; + rms->double_melt = false; return; } TALER_TESTING_interpreter_next (rms->is); @@ -988,14 +1033,15 @@ melt_run (void *cls, melt_fresh_amounts = default_melt_fresh_amounts; rms->is = is; rms->noreveal_index = UINT16_MAX; + TALER_refresh_master_setup_random (&rms->rms); for (num_fresh_coins = 0; NULL != melt_fresh_amounts[num_fresh_coins]; num_fresh_coins++) ; rms->num_fresh_coins = num_fresh_coins; - rms->fresh_pks = GNUNET_new_array - (num_fresh_coins, - struct TALER_EXCHANGE_DenomPublicKey); + rms->fresh_pks = GNUNET_new_array ( + num_fresh_coins, + struct TALER_EXCHANGE_DenomPublicKey); { struct TALER_Amount melt_amount; struct TALER_Amount fresh_amount; @@ -1005,8 +1051,9 @@ melt_run (void *cls, bool age_restricted; if (NULL == (coin_command - = TALER_TESTING_interpreter_lookup_command - (is, rms->coin_reference))) + = TALER_TESTING_interpreter_lookup_command ( + is, + rms->coin_reference))) { GNUNET_break (0); TALER_TESTING_interpreter_fail (rms->is); @@ -1022,7 +1069,6 @@ melt_run (void *cls, TALER_TESTING_interpreter_fail (rms->is); return; } - if (GNUNET_OK != TALER_TESTING_get_trait_age_commitment (coin_command, 0, @@ -1068,7 +1114,8 @@ melt_run (void *cls, GNUNET_break (0); GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to parse amount `%s' at index %u\n", - melt_fresh_amounts[i], i); + melt_fresh_amounts[i], + i); TALER_TESTING_interpreter_fail (rms->is); return; } @@ -1095,7 +1142,14 @@ melt_run (void *cls, TALER_denom_pub_deep_copy (&rms->fresh_pks[i].key, &fresh_pk->key); } /* end for */ - GNUNET_assert (NULL == rms->refresh_data); + + rms->refresh_data.melt_priv = *rms->melt_priv; + rms->refresh_data.melt_amount = melt_amount; + rms->refresh_data.melt_sig = *melt_sig; + rms->refresh_data.melt_pk = *melt_denom_pub; + rms->refresh_data.fresh_pks = rms->fresh_pks; + rms->refresh_data.fresh_pks_len = num_fresh_coins; +/* FIXME-oec: is this needed _here_? { struct TALER_AgeCommitment *ac = NULL; @@ -1114,23 +1168,13 @@ melt_run (void *cls, ac)); } - rms->refresh_data - = TALER_EXCHANGE_refresh_prepare (rms->melt_priv, - &melt_amount, - melt_sig, - melt_denom_pub, - ac, - num_fresh_coins, - rms->fresh_pks); - } - if (NULL == rms->refresh_data) - { - GNUNET_break (0); - TALER_TESTING_interpreter_fail (rms->is); - return; + rms->refresh_data.age_commitment = ac } +*/ + rms->rmh = TALER_EXCHANGE_melt (is->exchange, - rms->refresh_data, + &rms->rms, + &rms->refresh_data, &melt_cb, rms); @@ -1162,7 +1206,8 @@ melt_cleanup (void *cls, { GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Command %u (%s) did not complete\n", - rms->is->ip, rms->is->commands[rms->is->ip].label); + rms->is->ip, + rms->is->commands[rms->is->ip].label); TALER_EXCHANGE_melt_cancel (rms->rmh); rms->rmh = NULL; } @@ -1175,11 +1220,9 @@ melt_cleanup (void *cls, { for (unsigned int i = 0; i < rms->num_fresh_coins; i++) TALER_denom_pub_free (&rms->fresh_pks[i].key); + GNUNET_free (rms->fresh_pks); } - GNUNET_free (rms->fresh_pks); - rms->fresh_pks = NULL; - json_decref (rms->refresh_data); - rms->refresh_data = NULL; + GNUNET_free (rms->mbds); GNUNET_free (rms->melt_fresh_amounts); GNUNET_free (rms); } @@ -1215,6 +1258,9 @@ melt_traits (void *cls, rms->melt_priv), TALER_TESTING_make_trait_age_commitment (index, rms->age_commitment), + TALER_TESTING_make_trait_exchange_wd_value (index, + &rms->mbds[index].alg_value), + TALER_TESTING_make_trait_refresh_secret (&rms->rms), TALER_TESTING_trait_end () }; @@ -1288,7 +1334,8 @@ TALER_TESTING_cmd_melt (const char *label, rms = GNUNET_new (struct RefreshMeltState); rms->coin_reference = coin_reference; rms->expected_response_code = expected_response_code; - va_start (ap, expected_response_code); + va_start (ap, + expected_response_code); GNUNET_assert (GNUNET_OK == parse_amounts (rms, ap)); va_end (ap); @@ -1318,8 +1365,9 @@ TALER_TESTING_cmd_melt_double (const char *label, rms = GNUNET_new (struct RefreshMeltState); rms->coin_reference = coin_reference; rms->expected_response_code = expected_response_code; - rms->double_melt = GNUNET_YES; - va_start (ap, expected_response_code); + rms->double_melt = true; + va_start (ap, + expected_response_code); GNUNET_assert (GNUNET_OK == parse_amounts (rms, ap)); va_end (ap); @@ -1389,6 +1437,8 @@ refresh_reveal_traits (void *cls, &rrs->num_fresh_coins), TALER_TESTING_make_trait_fresh_coins ( (const struct TALER_TESTING_FreshCoinData **) &rrs->fresh_coins), + TALER_TESTING_make_trait_planchet_secrets (index, + &rrs->psa[index]), TALER_TESTING_trait_end () }; diff --git a/src/testing/testing_api_cmd_refund.c b/src/testing/testing_api_cmd_refund.c index c288e9e15..5dae9e57c 100644 --- a/src/testing/testing_api_cmd_refund.c +++ b/src/testing/testing_api_cmd_refund.c @@ -235,7 +235,6 @@ TALER_TESTING_cmd_refund (const char *label, struct RefundState *rs; rs = GNUNET_new (struct RefundState); - rs->expected_response_code = expected_response_code; rs->refund_amount = refund_amount; rs->coin_reference = coin_reference; diff --git a/src/testing/testing_api_cmd_serialize_keys.c b/src/testing/testing_api_cmd_serialize_keys.c index d3b34a934..ef912bf51 100644 --- a/src/testing/testing_api_cmd_serialize_keys.c +++ b/src/testing/testing_api_cmd_serialize_keys.c @@ -233,14 +233,6 @@ connect_with_state_cleanup (void *cls, } -/** - * Make a serialize-keys CMD. It will ask for - * keys serialization __and__ disconnect from the - * exchange. - * - * @param label CMD label - * @return the CMD. - */ struct TALER_TESTING_Command TALER_TESTING_cmd_serialize_keys (const char *label) { @@ -261,16 +253,6 @@ TALER_TESTING_cmd_serialize_keys (const char *label) } -/** - * Make a connect-with-state CMD. This command - * will use a serialized key state to reconnect - * to the exchange. - * - * @param label command label - * @param state_reference label of a CMD offering - * a serialized key state. - * @return the CMD. - */ struct TALER_TESTING_Command TALER_TESTING_cmd_connect_with_state (const char *label, const char *state_reference) diff --git a/src/testing/testing_api_cmd_withdraw.c b/src/testing/testing_api_cmd_withdraw.c index e3c129172..e5e8adfd5 100644 --- a/src/testing/testing_api_cmd_withdraw.c +++ b/src/testing/testing_api_cmd_withdraw.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2018-2021 Taler Systems SA + Copyright (C) 2018-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -100,6 +100,22 @@ struct WithdrawState */ struct TALER_ReservePublicKeyP reserve_pub; + /** + * Private key of the coin. + */ + struct TALER_CoinSpendPrivateKeyP coin_priv; + + /** + * Blinding key used during the operation. + */ + union TALER_DenominationBlindingKeyP bks; + + /** + * Values contributed from the exchange during the + * withdraw protocol. + */ + struct TALER_ExchangeWithdrawValues exchange_vals; + /** * Interpreter state (during command). */ @@ -114,7 +130,7 @@ struct WithdrawState /** * Private key material of the coin, set by the interpreter. */ - struct TALER_PlanchetSecretsP ps; + struct TALER_PlanchetMasterSecretP ps; /** * An age > 0 signifies age restriction is required @@ -276,6 +292,9 @@ reserve_withdraw_cb (void *cls, case MHD_HTTP_OK: TALER_denom_sig_deep_copy (&ws->sig, &wr->details.success.sig); + ws->coin_priv = wr->details.success.coin_priv; + ws->bks = wr->details.success.bks; + ws->exchange_vals = wr->details.success.exchange_vals; if (0 != ws->total_backoff.rel_value_us) { GNUNET_log (GNUNET_ERROR_TYPE_INFO, @@ -405,11 +424,11 @@ withdraw_run (void *cls, if (NULL == ws->reuse_coin_key_ref) { - TALER_planchet_setup_random (&ws->ps); + TALER_planchet_master_setup_random (&ws->ps); } else { - const struct TALER_CoinSpendPrivateKeyP *coin_priv; + const struct TALER_PlanchetMasterSecretP *ps; const struct TALER_TESTING_Command *cref; char *cstr; unsigned int index; @@ -423,11 +442,9 @@ withdraw_run (void *cls, GNUNET_assert (NULL != cref); GNUNET_free (cstr); GNUNET_assert (GNUNET_OK == - TALER_TESTING_get_trait_coin_priv (cref, - index, - &coin_priv)); - TALER_planchet_setup_random (&ws->ps); - ws->ps.coin_priv = *coin_priv; + TALER_TESTING_get_trait_planchet_secret (cref, + &ps)); + ws->ps = *ps; } if (NULL == ws->pk) @@ -547,11 +564,14 @@ withdraw_traits (void *cls, struct TALER_TESTING_Trait traits[] = { /* history entry MUST be first due to response code logic below! */ TALER_TESTING_make_trait_reserve_history (&ws->reserve_history), - TALER_TESTING_make_trait_coin_priv (index /* only one coin */, - &ws->ps.coin_priv), - TALER_TESTING_make_trait_blinding_key (index /* only one coin */, - &ws->ps.blinding_key), - TALER_TESTING_make_trait_denom_pub (index /* only one coin */, + TALER_TESTING_make_trait_coin_priv (0 /* only one coin */, + &ws->coin_priv), + TALER_TESTING_make_trait_planchet_secret (&ws->ps), + TALER_TESTING_make_trait_blinding_key (0 /* only one coin */, + &ws->bks), + TALER_TESTING_make_trait_exchange_wd_value (0 /* only one coin */, + &ws->exchange_vals), + TALER_TESTING_make_trait_denom_pub (0 /* only one coin */, ws->pk), TALER_TESTING_make_trait_denom_sig (index /* only one coin */, &ws->sig), diff --git a/src/testing/testing_api_helpers_bank.c b/src/testing/testing_api_helpers_bank.c index d3c7a2d73..0d8017e65 100644 --- a/src/testing/testing_api_helpers_bank.c +++ b/src/testing/testing_api_helpers_bank.c @@ -670,7 +670,7 @@ TALER_TESTING_prepare_fakebank (const char *config_filename, json_t * TALER_TESTING_make_wire_details (const char *payto) { - struct TALER_WireSalt salt; + struct TALER_WireSaltP salt; /* salt must be constant for aggregation tests! */ memset (&salt, diff --git a/src/testing/testing_api_helpers_exchange.c b/src/testing/testing_api_helpers_exchange.c index a5ce7fc4a..1eecbfeb3 100644 --- a/src/testing/testing_api_helpers_exchange.c +++ b/src/testing/testing_api_helpers_exchange.c @@ -375,17 +375,6 @@ fail: } -/** - * Prepare launching an exchange. Checks that the configured - * port is available, runs taler-exchange-dbinit. Does NOT - * launch the exchange process itself. - * - * @param config_filename configuration file to use - * @param reset_db should we reset the database? - * @param[out] ec will be set to the exchange configuration data - * @return #GNUNET_OK on success, #GNUNET_NO if test should be - * skipped, #GNUNET_SYSERR on test failure - */ enum GNUNET_GenericReturnValue TALER_TESTING_prepare_exchange (const char *config_filename, int reset_db, @@ -415,14 +404,6 @@ TALER_TESTING_prepare_exchange (const char *config_filename, } -/** - * Find denomination key matching the given amount. - * - * @param keys array of keys to search - * @param amount coin value to look for - * @param age_restricted must denomination support age restriction? - * @return NULL if no matching key was found - */ const struct TALER_EXCHANGE_DenomPublicKey * TALER_TESTING_find_pk (const struct TALER_EXCHANGE_Keys *keys, const struct TALER_Amount *amount, @@ -616,9 +597,9 @@ TALER_TESTING_setup_with_exchange (TALER_TESTING_Main main_cb, * @param[in] helpers the process handles. */ static void -stop_helpers (struct GNUNET_OS_Process *helpers[2]) +stop_helpers (struct GNUNET_OS_Process *helpers[3]) { - for (unsigned int i = 0; i<2; i++) + for (unsigned int i = 0; i<3; i++) { if (NULL == helpers[i]) continue; @@ -640,7 +621,7 @@ stop_helpers (struct GNUNET_OS_Process *helpers[2]) */ static enum GNUNET_GenericReturnValue start_helpers (const char *config_filename, - struct GNUNET_OS_Process *helpers[2]) + struct GNUNET_OS_Process *helpers[3]) { char *dir; const struct GNUNET_OS_ProjectData *pd; @@ -686,9 +667,26 @@ start_helpers (const char *config_filename, NULL); GNUNET_free (fn); } + { + char *fn; + + GNUNET_asprintf (&fn, + "%s/%s", + dir, + "taler-exchange-secmod-cs"); + helpers[2] = GNUNET_OS_start_process (GNUNET_OS_INHERIT_STD_ALL, + NULL, NULL, NULL, + fn, + "taler-exchange-secmod-cs", + "-c", config_filename, + "-L", "INFO", + NULL); + GNUNET_free (fn); + } GNUNET_free (dir); if ( (NULL == helpers[0]) || - (NULL == helpers[1]) ) + (NULL == helpers[1]) || + (NULL == helpers[2]) ) { stop_helpers (helpers); return GNUNET_SYSERR; @@ -704,7 +702,7 @@ TALER_TESTING_setup_with_exchange_cfg ( { const struct TALER_TESTING_SetupContext *setup_ctx = cls; struct GNUNET_OS_Process *exchanged; - struct GNUNET_OS_Process *helpers[2]; + struct GNUNET_OS_Process *helpers[3]; unsigned long long port; char *serve; char *base_url; @@ -763,6 +761,7 @@ TALER_TESTING_setup_with_exchange_cfg ( #endif "taler-exchange-httpd", "taler-exchange-httpd", + "-L", "INFO", "-a", /* some tests may need timetravel */ "-c", setup_ctx->config_filename, #if GNU_PARALLEL diff --git a/src/testing/testing_api_loop.c b/src/testing/testing_api_loop.c index 7a25bed64..784d3c9ec 100644 --- a/src/testing/testing_api_loop.c +++ b/src/testing/testing_api_loop.c @@ -36,13 +36,7 @@ */ static struct GNUNET_DISK_PipeHandle *sigpipe; -/** - * Lookup command by label. - * - * @param is interpreter state to search - * @param label label to look for - * @return NULL if command was not found - */ + const struct TALER_TESTING_Command * TALER_TESTING_interpreter_lookup_command (struct TALER_TESTING_Interpreter *is, const char *label) @@ -229,11 +223,6 @@ TALER_TESTING_interpreter_get_current_label (struct } -/** - * Run the main interpreter loop that performs exchange operations. - * - * @param cls contains the `struct TALER_TESTING_Interpreter` - */ static void interpreter_run (void *cls) { @@ -691,7 +680,7 @@ main_wrapper_exchange_connect (void *cls) * * @param[in,out] is state to initialize */ -static int +static enum GNUNET_GenericReturnValue load_keys (struct TALER_TESTING_Interpreter *is) { char *fn; @@ -774,7 +763,7 @@ load_keys (struct TALER_TESTING_Interpreter *is) * * @param[in,out] is state to initialize */ -static int +static enum GNUNET_GenericReturnValue load_urls (struct TALER_TESTING_Interpreter *is) { if (GNUNET_OK != @@ -804,7 +793,7 @@ load_urls (struct TALER_TESTING_Interpreter *is) } -int +enum GNUNET_GenericReturnValue TALER_TESTING_setup (TALER_TESTING_Main main_cb, void *main_cb_cls, const struct GNUNET_CONFIGURATION_Handle *cfg, @@ -839,7 +828,8 @@ TALER_TESTING_setup (TALER_TESTING_Main main_cb, is.ctx = GNUNET_CURL_init (&GNUNET_CURL_gnunet_scheduler_reschedule, &is.rc); - GNUNET_CURL_enable_async_scope_header (is.ctx, "Taler-Correlation-Id"); + GNUNET_CURL_enable_async_scope_header (is.ctx, + "Taler-Correlation-Id"); GNUNET_assert (NULL != is.ctx); is.rc = GNUNET_CURL_gnunet_rc_create (is.ctx); diff --git a/src/util/.gitignore b/src/util/.gitignore index f25567f32..c5f8c76dd 100644 --- a/src/util/.gitignore +++ b/src/util/.gitignore @@ -1,8 +1,11 @@ taler-config test_payto taler-exchange-secmod-rsa +taler-exchange-secmod-cs taler-exchange-secmod-eddsa test_helper_rsa test_helper_rsa_home/ +test_helper_cs +test_helper_cs_home/ test_helper_eddsa test_helper_eddsa_home/ diff --git a/src/util/Makefile.am b/src/util/Makefile.am index 35e580347..997b49f29 100644 --- a/src/util/Makefile.am +++ b/src/util/Makefile.am @@ -12,17 +12,20 @@ pkgcfgdir = $(prefix)/share/taler/config.d/ pkgcfg_DATA = \ paths.conf \ taler-exchange-secmod-eddsa.conf \ - taler-exchange-secmod-rsa.conf + taler-exchange-secmod-rsa.conf \ + taler-exchange-secmod-cs.conf EXTRA_DIST = \ $(pkgcfg_DATA) \ taler-config.in \ test_helper_eddsa.conf \ - test_helper_rsa.conf + test_helper_rsa.conf \ + test_helper_cs.conf bin_PROGRAMS = \ taler-exchange-secmod-eddsa \ - taler-exchange-secmod-rsa + taler-exchange-secmod-rsa \ + taler-exchange-secmod-cs bin_SCRIPTS = \ taler-config @@ -48,6 +51,16 @@ taler_exchange_secmod_rsa_LDADD = \ $(LIBGCRYPT_LIBS) \ $(XLIB) +taler_exchange_secmod_cs_SOURCES = \ + taler-exchange-secmod-cs.c taler-exchange-secmod-cs.h \ + secmod_common.c secmod_common.h +taler_exchange_secmod_cs_LDADD = \ + libtalerutil.la \ + -lgnunetutil \ + -lpthread \ + $(LIBGCRYPT_LIBS) \ + $(XLIB) + taler_exchange_secmod_eddsa_SOURCES = \ taler-exchange-secmod-eddsa.c taler-exchange-secmod-eddsa.h \ secmod_common.c secmod_common.h @@ -68,6 +81,7 @@ libtalerutil_la_SOURCES = \ crypto.c \ crypto_helper_common.c crypto_helper_common.h \ crypto_helper_rsa.c \ + crypto_helper_cs.c \ crypto_helper_esign.c \ crypto_wire.c \ denom.c \ @@ -105,6 +119,7 @@ check_PROGRAMS = \ test_crypto \ test_helper_eddsa \ test_helper_rsa \ + test_helper_cs \ test_payto \ test_url @@ -142,6 +157,12 @@ test_helper_rsa_LDADD = \ -lgnunetutil \ libtalerutil.la +test_helper_cs_SOURCES = \ + test_helper_cs.c +test_helper_cs_LDADD = \ + -lgnunetutil \ + libtalerutil.la + test_url_SOURCES = \ test_url.c test_url_LDADD = \ diff --git a/src/util/config.c b/src/util/config.c index d368d346e..8123b7343 100644 --- a/src/util/config.c +++ b/src/util/config.c @@ -23,15 +23,6 @@ #include "taler_util.h" -/** - * Obtain denomination amount from configuration file. - * - * @param cfg configuration to use - * @param section section of the configuration to access - * @param option option of the configuration to access - * @param[out] denom set to the amount found in configuration - * @return #GNUNET_OK on success, #GNUNET_SYSERR on error - */ enum GNUNET_GenericReturnValue TALER_config_get_amount (const struct GNUNET_CONFIGURATION_Handle *cfg, const char *section, @@ -67,14 +58,6 @@ TALER_config_get_amount (const struct GNUNET_CONFIGURATION_Handle *cfg, } -/** - * Load our currency from the @a cfg (in section [taler] - * the option "CURRENCY"). - * - * @param cfg configuration to use - * @param[out] currency where to write the result - * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure - */ enum GNUNET_GenericReturnValue TALER_config_get_currency (const struct GNUNET_CONFIGURATION_Handle *cfg, char **currency) diff --git a/src/util/crypto.c b/src/util/crypto.c index 0071c2d72..6bea984f3 100644 --- a/src/util/crypto.c +++ b/src/util/crypto.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2014-2017 Taler Systems SA + Copyright (C) 2014-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -120,7 +120,6 @@ TALER_link_derive_transfer_secret ( GNUNET_CRYPTO_ecdh_eddsa (&trans_priv->ecdhe_priv, &coin_pub.eddsa_pub, &ts->key)); - } @@ -151,9 +150,30 @@ TALER_link_recover_transfer_secret ( void -TALER_planchet_setup_refresh (const struct TALER_TransferSecretP *secret_seed, - uint32_t coin_num_salt, - struct TALER_PlanchetSecretsP *ps) +TALER_planchet_master_setup_random ( + struct TALER_PlanchetMasterSecretP *ps) +{ + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG, + ps, + sizeof (*ps)); +} + + +void +TALER_refresh_master_setup_random ( + struct TALER_RefreshMasterSecretP *rms) +{ + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG, + rms, + sizeof (*rms)); +} + + +void +TALER_transfer_secret_to_planchet_secret ( + const struct TALER_TransferSecretP *secret_seed, + uint32_t coin_num_salt, + struct TALER_PlanchetMasterSecretP *ps) { uint32_t be_salt = htonl (coin_num_salt); @@ -171,33 +191,88 @@ TALER_planchet_setup_refresh (const struct TALER_TransferSecretP *secret_seed, void -TALER_planchet_setup_random (struct TALER_PlanchetSecretsP *ps) +TALER_planchet_secret_to_transfer_priv ( + const struct TALER_RefreshMasterSecretP *rms, + uint32_t cnc_num, + struct TALER_TransferPrivateKeyP *tpriv) { - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG, - ps, - sizeof (*ps)); + uint32_t be_salt = htonl (cnc_num); + + GNUNET_assert (GNUNET_OK == + GNUNET_CRYPTO_kdf (tpriv, + sizeof (*tpriv), + &be_salt, + sizeof (be_salt), + rms, + sizeof (*rms), + "taler-transfer-priv-derivation", + strlen ("taler-transfer-priv-derivation"), + NULL, 0)); +} + + +void +TALER_cs_withdraw_nonce_derive ( + const struct TALER_PlanchetMasterSecretP *ps, + struct TALER_CsNonce *nonce) +{ + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (nonce, + sizeof (*nonce), + "n", + strlen ("n"), + ps, + sizeof(*ps), + NULL, + 0)); +} + + +void +TALER_cs_refresh_nonce_derive ( + const struct TALER_RefreshMasterSecretP *rms, + uint32_t coin_num_salt, + struct TALER_CsNonce *nonce) +{ + uint32_t be_salt = htonl (coin_num_salt); + + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (nonce, + sizeof (*nonce), + &be_salt, + sizeof (be_salt), + "refresh-n", // FIXME: value used in spec? + strlen ("refresh-n"), + rms, + sizeof(*rms), + NULL, + 0)); } enum GNUNET_GenericReturnValue TALER_planchet_prepare (const struct TALER_DenominationPublicKey *dk, - const struct TALER_PlanchetSecretsP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinSpendPrivateKeyP *coin_priv, const struct TALER_AgeCommitmentHash *ach, struct TALER_CoinPubHash *c_hash, - struct TALER_PlanchetDetail *pd) + struct TALER_PlanchetDetail *pd + ) { struct TALER_CoinSpendPublicKeyP coin_pub; - GNUNET_CRYPTO_eddsa_key_get_public (&ps->coin_priv.eddsa_priv, + GNUNET_assert (alg_values->cipher == dk->cipher); + GNUNET_CRYPTO_eddsa_key_get_public (&coin_priv->eddsa_priv, &coin_pub.eddsa_pub); if (GNUNET_OK != TALER_denom_blind (dk, - &ps->blinding_key, + bks, ach, &coin_pub, + alg_values, c_hash, - &pd->coin_ev, - &pd->coin_ev_size)) + &pd->blinded_planchet)) { GNUNET_break (0); return GNUNET_SYSERR; @@ -208,21 +283,36 @@ TALER_planchet_prepare (const struct TALER_DenominationPublicKey *dk, } +void +TALER_planchet_detail_free (struct TALER_PlanchetDetail *pd) +{ + TALER_blinded_planchet_free (&pd->blinded_planchet); +} + + enum GNUNET_GenericReturnValue TALER_planchet_to_coin ( const struct TALER_DenominationPublicKey *dk, const struct TALER_BlindedDenominationSignature *blind_sig, - const struct TALER_PlanchetSecretsP *ps, + const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinSpendPrivateKeyP *coin_priv, const struct TALER_AgeCommitmentHash *ach, const struct TALER_CoinPubHash *c_hash, + const struct TALER_ExchangeWithdrawValues *alg_values, struct TALER_FreshCoin *coin) { - struct TALER_DenominationSignature sig; - + if ( (dk->cipher != blind_sig->cipher) || + (dk->cipher != alg_values->cipher) ) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } if (GNUNET_OK != - TALER_denom_sig_unblind (&sig, + TALER_denom_sig_unblind (&coin->sig, blind_sig, - &ps->blinding_key, + bks, + c_hash, + alg_values, dk)) { GNUNET_break_op (0); @@ -230,15 +320,15 @@ TALER_planchet_to_coin ( } if (GNUNET_OK != TALER_denom_pub_verify (dk, - &sig, + &coin->sig, c_hash)) { GNUNET_break_op (0); - TALER_denom_sig_free (&sig); + TALER_denom_sig_free (&coin->sig); return GNUNET_SYSERR; } - coin->sig = sig; - coin->coin_priv = ps->coin_priv; + + coin->coin_priv = *coin_priv; coin->h_age_commitment = ach; return GNUNET_OK; } @@ -301,9 +391,8 @@ TALER_refresh_get_commitment (struct TALER_RefreshCommitmentP *rc, { const struct TALER_RefreshCoinData *rcd = &rce->new_coins[j]; - GNUNET_CRYPTO_hash_context_read (hash_context, - rcd->coin_ev, - rcd->coin_ev_size); + TALER_blinded_planchet_hash (&rcd->blinded_planchet, + hash_context); } } @@ -313,17 +402,6 @@ TALER_refresh_get_commitment (struct TALER_RefreshCommitmentP *rc, } -void -TALER_coin_ev_hash (const void *coin_ev, - size_t coin_ev_size, - struct TALER_BlindedCoinHash *bch) -{ - GNUNET_CRYPTO_hash (coin_ev, - coin_ev_size, - &bch->hash); -} - - void TALER_coin_pub_hash (const struct TALER_CoinSpendPublicKeyP *coin_pub, const struct TALER_AgeCommitmentHash *ach, @@ -347,11 +425,9 @@ TALER_coin_pub_hash (const struct TALER_CoinSpendPublicKeyP *coin_pub, GNUNET_memcpy (&data[0], &coin_pub->eddsa_pub, key_s); - GNUNET_memcpy (&data[key_s], ach, age_s); - GNUNET_CRYPTO_hash (&data, key_s + age_s, &coin_h->hash); diff --git a/src/util/crypto_helper_cs.c b/src/util/crypto_helper_cs.c new file mode 100644 index 000000000..874679cf0 --- /dev/null +++ b/src/util/crypto_helper_cs.c @@ -0,0 +1,799 @@ +/* + This file is part of TALER + Copyright (C) 2020, 2021 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see +*/ +/** + * @file util/crypto_helper_cs.c + * @brief utility functions for running out-of-process private key operations + * @author Christian Grothoff + */ +#include "platform.h" +#include "taler_util.h" +#include "taler_signatures.h" +#include "taler-exchange-secmod-cs.h" +#include +#include "crypto_helper_common.h" + + +struct TALER_CRYPTO_CsDenominationHelper +{ + /** + * Function to call with updates to available key material. + */ + TALER_CRYPTO_CsDenominationKeyStatusCallback dkc; + + /** + * Closure for @e dkc + */ + void *dkc_cls; + + /** + * Socket address of the denomination helper process. + * Used to reconnect if the connection breaks. + */ + struct sockaddr_un sa; + + /** + * The UNIX domain socket, -1 if we are currently not connected. + */ + int sock; + + /** + * Have we ever been sync'ed? + */ + bool synced; +}; + + +/** + * Disconnect from the helper process. Updates + * @e sock field in @a dh. + * + * @param[in,out] dh handle to tear down connection of + */ +static void +do_disconnect (struct TALER_CRYPTO_CsDenominationHelper *dh) +{ + GNUNET_break (0 == close (dh->sock)); + dh->sock = -1; + dh->synced = false; +} + + +/** + * Try to connect to the helper process. Updates + * @e sock field in @a dh. + * + * @param[in,out] dh handle to establish connection for + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +try_connect (struct TALER_CRYPTO_CsDenominationHelper *dh) +{ + if (-1 != dh->sock) + return GNUNET_OK; + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Establishing connection!\n"); + dh->sock = socket (AF_UNIX, + SOCK_STREAM, + 0); + if (-1 == dh->sock) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "socket"); + return GNUNET_SYSERR; + } + if (0 != + connect (dh->sock, + (const struct sockaddr *) &dh->sa, + sizeof (dh->sa))) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "connect", + dh->sa.sun_path); + do_disconnect (dh); + return GNUNET_SYSERR; + } + TALER_CRYPTO_helper_cs_poll (dh); + return GNUNET_OK; +} + + +struct TALER_CRYPTO_CsDenominationHelper * +TALER_CRYPTO_helper_cs_connect ( + const struct GNUNET_CONFIGURATION_Handle *cfg, + TALER_CRYPTO_CsDenominationKeyStatusCallback dkc, + void *dkc_cls) +{ + struct TALER_CRYPTO_CsDenominationHelper *dh; + char *unixpath; + + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_filename (cfg, + "taler-exchange-secmod-cs", + "UNIXPATH", + &unixpath)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "UNIXPATH"); + return NULL; + } + /* we use >= here because we want the sun_path to always + be 0-terminated */ + if (strlen (unixpath) >= sizeof (dh->sa.sun_path)) + { + GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "UNIXPATH", + "path too long"); + GNUNET_free (unixpath); + return NULL; + } + dh = GNUNET_new (struct TALER_CRYPTO_CsDenominationHelper); + dh->dkc = dkc; + dh->dkc_cls = dkc_cls; + dh->sa.sun_family = AF_UNIX; + strncpy (dh->sa.sun_path, + unixpath, + sizeof (dh->sa.sun_path) - 1); + GNUNET_free (unixpath); + dh->sock = -1; + if (GNUNET_OK != + try_connect (dh)) + { + TALER_CRYPTO_helper_cs_disconnect (dh); + return NULL; + } + return dh; +} + + +/** + * Handle a #TALER_HELPER_CS_MT_AVAIL message from the helper. + * + * @param dh helper context + * @param hdr message that we received + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +handle_mt_avail (struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct GNUNET_MessageHeader *hdr) +{ + const struct TALER_CRYPTO_CsKeyAvailableNotification *kan + = (const struct TALER_CRYPTO_CsKeyAvailableNotification *) hdr; + const char *buf = (const char *) &kan[1]; + const char *section_name; + uint16_t snl; + + if (sizeof (*kan) > ntohs (hdr->size)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + snl = ntohs (kan->section_name_len); + if (ntohs (hdr->size) != sizeof (*kan) + snl) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + if (0 == snl) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + section_name = buf; + if ('\0' != section_name[snl - 1]) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + + { + struct TALER_DenominationPublicKey denom_pub; + struct TALER_CsPubHashP h_cs; + + denom_pub.cipher = TALER_DENOMINATION_CS; + denom_pub.details.cs_public_key = kan->denom_pub; + + TALER_cs_pub_hash (&denom_pub.details.cs_public_key, &h_cs); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received CS key %s (%s)\n", + GNUNET_h2s (&h_cs.hash), + section_name); + if (GNUNET_OK != + TALER_exchange_secmod_cs_verify ( + &h_cs, + section_name, + GNUNET_TIME_timestamp_ntoh (kan->anchor_time), + GNUNET_TIME_relative_ntoh (kan->duration_withdraw), + &kan->secm_pub, + &kan->secm_sig)) + { + GNUNET_break_op (0); + TALER_denom_pub_free (&denom_pub); + return GNUNET_SYSERR; + } + dh->dkc (dh->dkc_cls, + section_name, + GNUNET_TIME_timestamp_ntoh (kan->anchor_time), + GNUNET_TIME_relative_ntoh (kan->duration_withdraw), + &h_cs, + &denom_pub, + &kan->secm_pub, + &kan->secm_sig); + TALER_denom_pub_free (&denom_pub); + } + return GNUNET_OK; +} + + +/** + * Handle a #TALER_HELPER_CS_MT_PURGE message from the helper. + * + * @param dh helper context + * @param hdr message that we received + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +handle_mt_purge (struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct GNUNET_MessageHeader *hdr) +{ + const struct TALER_CRYPTO_CsKeyPurgeNotification *pn + = (const struct TALER_CRYPTO_CsKeyPurgeNotification *) hdr; + + if (sizeof (*pn) != ntohs (hdr->size)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received revocation of denomination key %s\n", + GNUNET_h2s (&pn->h_cs.hash)); + dh->dkc (dh->dkc_cls, + NULL, + GNUNET_TIME_UNIT_ZERO_TS, + GNUNET_TIME_UNIT_ZERO, + &pn->h_cs, + NULL, + NULL, + NULL); + return GNUNET_OK; +} + + +void +TALER_CRYPTO_helper_cs_poll (struct TALER_CRYPTO_CsDenominationHelper *dh) +{ + char buf[UINT16_MAX]; + size_t off = 0; + unsigned int retry_limit = 3; + const struct GNUNET_MessageHeader *hdr + = (const struct GNUNET_MessageHeader *) buf; + + if (GNUNET_OK != + try_connect (dh)) + return; /* give up */ + while (1) + { + uint16_t msize; + ssize_t ret; + + ret = recv (dh->sock, + buf + off, + sizeof (buf) - off, + (dh->synced && (0 == off)) + ? MSG_DONTWAIT + : 0); + if (ret < 0) + { + if (EINTR == errno) + continue; + if (EAGAIN == errno) + { + GNUNET_assert (dh->synced); + GNUNET_assert (0 == off); + break; + } + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "recv"); + do_disconnect (dh); + if (0 == retry_limit) + return; /* give up */ + if (GNUNET_OK != + try_connect (dh)) + return; /* give up */ + retry_limit--; + continue; + } + if (0 == ret) + { + GNUNET_break (0 == off); + return; + } + off += ret; +more: + if (off < sizeof (struct GNUNET_MessageHeader)) + continue; + msize = ntohs (hdr->size); + if (off < msize) + continue; + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received message of type %u and length %u\n", + (unsigned int) ntohs (hdr->type), + (unsigned int) msize); + switch (ntohs (hdr->type)) + { + case TALER_HELPER_CS_MT_AVAIL: + if (GNUNET_OK != + handle_mt_avail (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return; + } + break; + case TALER_HELPER_CS_MT_PURGE: + if (GNUNET_OK != + handle_mt_purge (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return; + } + break; + case TALER_HELPER_CS_SYNCED: + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Now synchronized with CS helper\n"); + dh->synced = true; + break; + default: + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Received unexpected message of type %d (len: %u)\n", + (unsigned int) ntohs (hdr->type), + (unsigned int) msize); + GNUNET_break_op (0); + do_disconnect (dh); + return; + } + memmove (buf, + &buf[msize], + off - msize); + off -= msize; + goto more; + } +} + + +enum TALER_ErrorCode +TALER_CRYPTO_helper_cs_sign ( + struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_BlindedCsPlanchet *blinded_planchet, + struct TALER_BlindedDenominationSignature *bs) +{ + enum TALER_ErrorCode ec = TALER_EC_INVALID; + + bs->cipher = TALER_DENOMINATION_INVALID; + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Starting signature process\n"); + if (GNUNET_OK != + try_connect (dh)) + { + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Failed to connect to helper\n"); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + } + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Requesting signature\n"); + { + char buf[sizeof (struct TALER_CRYPTO_CsSignRequest)]; + struct TALER_CRYPTO_CsSignRequest *sr + = (struct TALER_CRYPTO_CsSignRequest *) buf; + + sr->header.size = htons (sizeof (buf)); + sr->header.type = htons (TALER_HELPER_CS_MT_REQ_SIGN); + sr->reserved = htonl (0); + sr->h_cs = *h_cs; + sr->planchet = *blinded_planchet; + if (GNUNET_OK != + TALER_crypto_helper_send_all (dh->sock, + buf, + sizeof (buf))) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "send"); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + } + } + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Awaiting reply\n"); + { + char buf[UINT16_MAX]; + size_t off = 0; + const struct GNUNET_MessageHeader *hdr + = (const struct GNUNET_MessageHeader *) buf; + bool finished = false; + + while (1) + { + uint16_t msize; + ssize_t ret; + + ret = recv (dh->sock, + &buf[off], + sizeof (buf) - off, + (finished && (0 == off)) + ? MSG_DONTWAIT + : 0); + if (ret < 0) + { + if (EINTR == errno) + continue; + if (EAGAIN == errno) + { + GNUNET_assert (finished); + GNUNET_assert (0 == off); + return ec; + } + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "recv"); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + break; + } + if (0 == ret) + { + GNUNET_break (0 == off); + if (! finished) + ec = TALER_EC_EXCHANGE_SIGNKEY_HELPER_BUG; + return ec; + } + off += ret; +more: + if (off < sizeof (struct GNUNET_MessageHeader)) + continue; + msize = ntohs (hdr->size); + if (off < msize) + continue; + switch (ntohs (hdr->type)) + { + case TALER_HELPER_CS_MT_RES_SIGNATURE: + if (msize < sizeof (struct TALER_CRYPTO_SignResponse)) + { + GNUNET_break_op (0); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + if (finished) + { + GNUNET_break_op (0); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + { + const struct TALER_CRYPTO_SignResponse *sr = + (const struct TALER_CRYPTO_SignResponse *) buf; + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received signature\n"); + ec = TALER_EC_NONE; + finished = true; + bs->cipher = TALER_DENOMINATION_CS; + bs->details.blinded_cs_answer = sr->cs_answer; + break; + } + case TALER_HELPER_CS_MT_RES_SIGN_FAILURE: + if (msize != sizeof (struct TALER_CRYPTO_SignFailure)) + { + GNUNET_break_op (0); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + { + const struct TALER_CRYPTO_SignFailure *sf = + (const struct TALER_CRYPTO_SignFailure *) buf; + + ec = (enum TALER_ErrorCode) ntohl (sf->ec); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Signing failed!\n"); + finished = true; + break; + } + case TALER_HELPER_CS_MT_AVAIL: + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received new key!\n"); + if (GNUNET_OK != + handle_mt_avail (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + break; /* while(1) loop ensures we recvfrom() again */ + case TALER_HELPER_CS_MT_PURGE: + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received revocation!\n"); + if (GNUNET_OK != + handle_mt_purge (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + break; /* while(1) loop ensures we recvfrom() again */ + case TALER_HELPER_CS_SYNCED: + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Synchronized add odd time with CS helper!\n"); + dh->synced = true; + break; + default: + GNUNET_break_op (0); + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Received unexpected message of type %u\n", + ntohs (hdr->type)); + do_disconnect (dh); + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + goto end; + } + memmove (buf, + &buf[msize], + off - msize); + off -= msize; + goto more; + } /* while(1) */ +end: + if (finished) + TALER_blinded_denom_sig_free (bs); + return ec; + } +} + + +void +TALER_CRYPTO_helper_cs_revoke ( + struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs) +{ + struct TALER_CRYPTO_CsRevokeRequest rr = { + .header.size = htons (sizeof (rr)), + .header.type = htons (TALER_HELPER_CS_MT_REQ_REVOKE), + .h_cs = *h_cs + }; + + if (GNUNET_OK != + try_connect (dh)) + return; /* give up */ + if (GNUNET_OK != + TALER_crypto_helper_send_all (dh->sock, + &rr, + sizeof (rr))) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "send"); + do_disconnect (dh); + return; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Requested revocation of denomination key %s\n", + GNUNET_h2s (&h_cs->hash)); +} + + +enum TALER_ErrorCode +TALER_CRYPTO_helper_cs_r_derive (struct TALER_CRYPTO_CsDenominationHelper *dh, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_CsNonce *nonce, + struct TALER_DenominationCSPublicRPairP *crp) +{ + enum TALER_ErrorCode ec = TALER_EC_INVALID; + + memset (crp, + 0, + sizeof (*crp)); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Starting R derivation process\n"); + if (GNUNET_OK != + try_connect (dh)) + { + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Failed to connect to helper\n"); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + } + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Requesting R\n"); + { + struct TALER_CRYPTO_CsRDeriveRequest rdr = { + .header.size = htons (sizeof (rdr)), + .header.type = htons (TALER_HELPER_CS_MT_REQ_RDERIVE), + .reserved = htonl (0), + .h_cs = *h_cs, + .nonce = *nonce + }; + + if (GNUNET_OK != + TALER_crypto_helper_send_all (dh->sock, + &rdr, + sizeof (rdr))) + { + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "send"); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + } + } + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Awaiting reply\n"); + { + char buf[UINT16_MAX]; + size_t off = 0; + const struct GNUNET_MessageHeader *hdr + = (const struct GNUNET_MessageHeader *) buf; + bool finished = false; + + while (1) + { + uint16_t msize; + ssize_t ret; + + ret = recv (dh->sock, + &buf[off], + sizeof (buf) - off, + (finished && (0 == off)) + ? MSG_DONTWAIT + : 0); + if (ret < 0) + { + if (EINTR == errno) + continue; + if (EAGAIN == errno) + { + GNUNET_assert (finished); + GNUNET_assert (0 == off); + return ec; + } + GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, + "recv"); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + } + if (0 == ret) + { + GNUNET_break (0 == off); + if (! finished) + return TALER_EC_EXCHANGE_SIGNKEY_HELPER_BUG; + return ec; + } + off += ret; +more: + if (off < sizeof (struct GNUNET_MessageHeader)) + continue; + msize = ntohs (hdr->size); + if (off < msize) + continue; + switch (ntohs (hdr->type)) + { + case TALER_HELPER_CS_MT_RES_RDERIVE: + if (msize != sizeof (struct TALER_CRYPTO_RDeriveResponse)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + if (finished) + { + GNUNET_break_op (0); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + { + const struct TALER_CRYPTO_RDeriveResponse *rdr = + (const struct TALER_CRYPTO_RDeriveResponse *) buf; + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received R\n"); + finished = true; + ec = TALER_EC_NONE; + *crp = rdr->r_pub; + break; + } + case TALER_HELPER_CS_MT_RES_RDERIVE_FAILURE: + if (msize != sizeof (struct TALER_CRYPTO_RDeriveFailure)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + { + const struct TALER_CRYPTO_RDeriveFailure *rdf = + (const struct TALER_CRYPTO_RDeriveFailure *) buf; + + ec = (enum TALER_ErrorCode) ntohl (rdf->ec); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "R derivation failed!\n"); + finished = true; + break; + } + case TALER_HELPER_CS_MT_AVAIL: + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received new key!\n"); + if (GNUNET_OK != + handle_mt_avail (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + break; /* while(1) loop ensures we recvfrom() again */ + case TALER_HELPER_CS_MT_PURGE: + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Received revocation!\n"); + if (GNUNET_OK != + handle_mt_purge (dh, + hdr)) + { + GNUNET_break_op (0); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + break; /* while(1) loop ensures we recvfrom() again */ + case TALER_HELPER_CS_SYNCED: + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Synchronized add odd time with CS helper!\n"); + dh->synced = true; + break; + default: + GNUNET_break_op (0); + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Received unexpected message of type %u\n", + ntohs (hdr->type)); + do_disconnect (dh); + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + } + memmove (buf, + &buf[msize], + off - msize); + off -= msize; + goto more; + } /* while(1) */ + } +} + + +void +TALER_CRYPTO_helper_cs_disconnect ( + struct TALER_CRYPTO_CsDenominationHelper *dh) +{ + if (-1 != dh->sock) + do_disconnect (dh); + GNUNET_free (dh); +} + + +/* end of crypto_helper_cs.c */ diff --git a/src/util/crypto_helper_rsa.c b/src/util/crypto_helper_rsa.c index fbfc97702..d3f498c07 100644 --- a/src/util/crypto_helper_rsa.c +++ b/src/util/crypto_helper_rsa.c @@ -14,7 +14,7 @@ TALER; see the file COPYING. If not, see */ /** - * @file util/crypto_helper_denom.c + * @file util/crypto_helper_rsa.c * @brief utility functions for running out-of-process private key operations * @author Christian Grothoff */ @@ -387,18 +387,17 @@ more: } -struct TALER_BlindedDenominationSignature +enum TALER_ErrorCode TALER_CRYPTO_helper_rsa_sign ( struct TALER_CRYPTO_RsaDenominationHelper *dh, const struct TALER_RsaPubHashP *h_rsa, const void *msg, size_t msg_size, - enum TALER_ErrorCode *ec) + struct TALER_BlindedDenominationSignature *bs) { - struct TALER_BlindedDenominationSignature ds = { - .cipher = TALER_DENOMINATION_INVALID - }; + enum TALER_ErrorCode ec = TALER_EC_INVALID; + bs->cipher = TALER_DENOMINATION_INVALID; GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting signature process\n"); if (GNUNET_OK != @@ -406,8 +405,7 @@ TALER_CRYPTO_helper_rsa_sign ( { GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Failed to connect to helper\n"); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; - return ds; + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; } GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, @@ -432,8 +430,7 @@ TALER_CRYPTO_helper_rsa_sign ( GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send"); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; - return ds; + return TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; } } @@ -446,7 +443,6 @@ TALER_CRYPTO_helper_rsa_sign ( = (const struct GNUNET_MessageHeader *) buf; bool finished = false; - *ec = TALER_EC_INVALID; while (1) { uint16_t msize; @@ -466,20 +462,20 @@ TALER_CRYPTO_helper_rsa_sign ( { GNUNET_assert (finished); GNUNET_assert (0 == off); - return ds; + return ec; } GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recv"); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE; break; } if (0 == ret) { GNUNET_break (0 == off); if (! finished) - *ec = TALER_EC_EXCHANGE_SIGNKEY_HELPER_BUG; - return ds; + ec = TALER_EC_EXCHANGE_SIGNKEY_HELPER_BUG; + return ec; } off += ret; more: @@ -495,14 +491,14 @@ more: { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } if (finished) { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } { @@ -517,15 +513,15 @@ more: { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received signature\n"); - *ec = TALER_EC_NONE; + ec = TALER_EC_NONE; finished = true; - ds.cipher = TALER_DENOMINATION_RSA; - ds.details.blinded_rsa_signature = rsa_signature; + bs->cipher = TALER_DENOMINATION_RSA; + bs->details.blinded_rsa_signature = rsa_signature; break; } case TALER_HELPER_RSA_MT_RES_SIGN_FAILURE: @@ -533,14 +529,14 @@ more: { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } { const struct TALER_CRYPTO_SignFailure *sf = (const struct TALER_CRYPTO_SignFailure *) buf; - *ec = (enum TALER_ErrorCode) ntohl (sf->ec); + ec = (enum TALER_ErrorCode) ntohl (sf->ec); GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Signing failed!\n"); finished = true; @@ -555,7 +551,7 @@ more: { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } break; /* while(1) loop ensures we recvfrom() again */ @@ -568,7 +564,7 @@ more: { GNUNET_break_op (0); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } break; /* while(1) loop ensures we recvfrom() again */ @@ -583,7 +579,7 @@ more: "Received unexpected message of type %u\n", ntohs (hdr->type)); do_disconnect (dh); - *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; + ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG; goto end; } memmove (buf, @@ -594,8 +590,8 @@ more: } /* while(1) */ end: if (finished) - TALER_blinded_denom_sig_free (&ds); - return ds; + TALER_blinded_denom_sig_free (bs); + return ec; } } diff --git a/src/util/crypto_wire.c b/src/util/crypto_wire.c index e1c7d9646..144b8ee9a 100644 --- a/src/util/crypto_wire.c +++ b/src/util/crypto_wire.c @@ -64,7 +64,7 @@ TALER_exchange_wire_signature_make ( void TALER_merchant_wire_signature_hash (const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, struct TALER_MerchantWireHash *hc) { GNUNET_assert (GNUNET_YES == @@ -83,7 +83,7 @@ TALER_merchant_wire_signature_hash (const char *payto_uri, enum GNUNET_GenericReturnValue TALER_merchant_wire_signature_check ( const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, const struct TALER_MerchantPublicKeyP *merch_pub, const struct TALER_MerchantSignatureP *merch_sig) { @@ -105,7 +105,7 @@ TALER_merchant_wire_signature_check ( void TALER_merchant_wire_signature_make ( const char *payto_uri, - const struct TALER_WireSalt *salt, + const struct TALER_WireSaltP *salt, const struct TALER_MerchantPrivateKeyP *merch_priv, struct TALER_MerchantSignatureP *merch_sig) { diff --git a/src/util/denom.c b/src/util/denom.c index f7ab6ad1e..7c2c42c9e 100644 --- a/src/util/denom.c +++ b/src/util/denom.c @@ -34,6 +34,7 @@ TALER_denom_priv_create (struct TALER_DenominationPrivateKey *denom_priv, memset (denom_pub, 0, sizeof (*denom_pub)); + switch (cipher) { case TALER_DENOMINATION_INVALID: @@ -63,10 +64,17 @@ TALER_denom_priv_create (struct TALER_DenominationPrivateKey *denom_priv, denom_pub->details.rsa_public_key = GNUNET_CRYPTO_rsa_private_key_get_public ( denom_priv->details.rsa_private_key); - denom_priv->cipher = cipher; - denom_pub->cipher = cipher; + denom_priv->cipher = TALER_DENOMINATION_RSA; + denom_pub->cipher = TALER_DENOMINATION_RSA; + return GNUNET_OK; + case TALER_DENOMINATION_CS: + GNUNET_CRYPTO_cs_private_key_generate (&denom_priv->details.cs_private_key); + GNUNET_CRYPTO_cs_private_key_get_public ( + &denom_priv->details.cs_private_key, + &denom_pub->details.cs_public_key); + denom_priv->cipher = TALER_DENOMINATION_CS; + denom_pub->cipher = TALER_DENOMINATION_CS; return GNUNET_OK; - // TODO: add case for Clause-Schnorr default: GNUNET_break (0); } @@ -77,12 +85,16 @@ TALER_denom_priv_create (struct TALER_DenominationPrivateKey *denom_priv, enum GNUNET_GenericReturnValue TALER_denom_sign_blinded (struct TALER_BlindedDenominationSignature *denom_sig, const struct TALER_DenominationPrivateKey *denom_priv, - void *blinded_msg, - size_t blinded_msg_size) + const struct TALER_BlindedPlanchet *blinded_planchet) { memset (denom_sig, 0, sizeof (*denom_sig)); + if (blinded_planchet->cipher != denom_priv->cipher) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } switch (denom_priv->cipher) { case TALER_DENOMINATION_INVALID: @@ -92,8 +104,8 @@ TALER_denom_sign_blinded (struct TALER_BlindedDenominationSignature *denom_sig, denom_sig->details.blinded_rsa_signature = GNUNET_CRYPTO_rsa_sign_blinded ( denom_priv->details.rsa_private_key, - blinded_msg, - blinded_msg_size); + blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size); if (NULL == denom_sig->details.blinded_rsa_signature) { GNUNET_break (0); @@ -101,7 +113,26 @@ TALER_denom_sign_blinded (struct TALER_BlindedDenominationSignature *denom_sig, } denom_sig->cipher = TALER_DENOMINATION_RSA; return GNUNET_OK; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + { + struct GNUNET_CRYPTO_CsRSecret r[2]; + + GNUNET_CRYPTO_cs_r_derive ( + &blinded_planchet->details.cs_blinded_planchet.nonce.nonce, + &denom_priv->details.cs_private_key, + r); + denom_sig->details.blinded_cs_answer.b = + GNUNET_CRYPTO_cs_sign_derive (&denom_priv->details.cs_private_key, + r, + blinded_planchet->details. + cs_blinded_planchet.c, + &blinded_planchet->details. + cs_blinded_planchet.nonce.nonce, + &denom_sig->details.blinded_cs_answer. + s_scalar); + denom_sig->cipher = TALER_DENOMINATION_CS; + } + return GNUNET_OK; default: GNUNET_break (0); } @@ -114,6 +145,8 @@ TALER_denom_sig_unblind ( struct TALER_DenominationSignature *denom_sig, const struct TALER_BlindedDenominationSignature *bdenom_sig, const union TALER_DenominationBlindingKeyP *bks, + const struct TALER_CoinPubHash *c_hash, + const struct TALER_ExchangeWithdrawValues *alg_values, const struct TALER_DenominationPublicKey *denom_pub) { if (bdenom_sig->cipher != denom_pub->cipher) @@ -139,7 +172,30 @@ TALER_denom_sig_unblind ( } denom_sig->cipher = TALER_DENOMINATION_RSA; return GNUNET_OK; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + { + struct GNUNET_CRYPTO_CsBlindingSecret bs[2]; + struct GNUNET_CRYPTO_CsC c[2]; + struct TALER_DenominationCSPublicRPairP r_pub_blind; + + GNUNET_CRYPTO_cs_blinding_secrets_derive (&bks->nonce, + bs); + GNUNET_CRYPTO_cs_calc_blinded_c ( + bs, + alg_values->details.cs_values.r_pub, + &denom_pub->details.cs_public_key, + &c_hash->hash, + sizeof(struct GNUNET_HashCode), + c, + r_pub_blind.r_pub); + denom_sig->details.cs_signature.r_point + = r_pub_blind.r_pub[bdenom_sig->details.blinded_cs_answer.b]; + GNUNET_CRYPTO_cs_unblind (&bdenom_sig->details.blinded_cs_answer.s_scalar, + &bs[bdenom_sig->details.blinded_cs_answer.b], + &denom_sig->details.cs_signature.s_scalar); + denom_sig->cipher = TALER_DENOMINATION_CS; + return GNUNET_OK; + } default: GNUNET_break (0); } @@ -147,21 +203,6 @@ TALER_denom_sig_unblind ( } -void -TALER_blinding_secret_create (union TALER_DenominationBlindingKeyP *bs) -{ - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, - bs, - sizeof (*bs)); -} - - -/** - * Hash @a rsa. - * - * @param rsa key to hash - * @param[out] h_rsa where to write the result - */ void TALER_rsa_pub_hash (const struct GNUNET_CRYPTO_RsaPublicKey *rsa, struct TALER_RsaPubHashP *h_rsa) @@ -172,6 +213,16 @@ TALER_rsa_pub_hash (const struct GNUNET_CRYPTO_RsaPublicKey *rsa, } +void +TALER_cs_pub_hash (const struct GNUNET_CRYPTO_CsPublicKey *cs, + struct TALER_CsPubHashP *h_cs) +{ + GNUNET_CRYPTO_hash (cs, + sizeof(*cs), + &h_cs->hash); +} + + void TALER_denom_pub_hash (const struct TALER_DenominationPublicKey *denom_pub, struct TALER_DenominationHash *denom_hash) @@ -180,8 +231,8 @@ TALER_denom_pub_hash (const struct TALER_DenominationPublicKey *denom_pub, htonl (denom_pub->age_mask.mask), htonl ((uint32_t) denom_pub->cipher) }; - struct GNUNET_HashContext *hc; + hc = GNUNET_CRYPTO_hash_context_start (); GNUNET_CRYPTO_hash_context_read (hc, opt, @@ -202,7 +253,11 @@ TALER_denom_pub_hash (const struct TALER_DenominationPublicKey *denom_pub, GNUNET_free (buf); } break; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + GNUNET_CRYPTO_hash_context_read (hc, + &denom_pub->details.cs_public_key, + sizeof(denom_pub->details.cs_public_key)); + break; default: GNUNET_assert (0); } @@ -225,7 +280,13 @@ TALER_denom_priv_to_pub (const struct TALER_DenominationPrivateKey *denom_priv, = GNUNET_CRYPTO_rsa_private_key_get_public ( denom_priv->details.rsa_private_key); return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + denom_pub->cipher = TALER_DENOMINATION_CS; + denom_pub->age_mask = age_mask; + GNUNET_CRYPTO_cs_private_key_get_public ( + &denom_priv->details.cs_private_key, + &denom_pub->details.cs_public_key); + return; default: GNUNET_assert (0); } @@ -233,32 +294,52 @@ TALER_denom_priv_to_pub (const struct TALER_DenominationPrivateKey *denom_priv, enum GNUNET_GenericReturnValue -TALER_denom_blind (const struct TALER_DenominationPublicKey *dk, - const union TALER_DenominationBlindingKeyP *coin_bks, - const struct TALER_AgeCommitmentHash *ach, - const struct TALER_CoinSpendPublicKeyP *coin_pub, - struct TALER_CoinPubHash *c_hash, - void **coin_ev, - size_t *coin_ev_size) +TALER_denom_blind ( + const struct TALER_DenominationPublicKey *dk, + const union TALER_DenominationBlindingKeyP *coin_bks, + const struct TALER_AgeCommitmentHash *ach, + const struct TALER_CoinSpendPublicKeyP *coin_pub, + const struct TALER_ExchangeWithdrawValues *alg_values, + struct TALER_CoinPubHash *c_hash, + struct TALER_BlindedPlanchet *blinded_planchet) { + TALER_coin_pub_hash (coin_pub, + ach, + c_hash); switch (dk->cipher) { case TALER_DENOMINATION_RSA: - TALER_coin_pub_hash (coin_pub, - ach, - c_hash); + blinded_planchet->cipher = dk->cipher; if (GNUNET_YES != - GNUNET_CRYPTO_rsa_blind (&c_hash->hash, - &coin_bks->rsa_bks, - dk->details.rsa_public_key, - coin_ev, - coin_ev_size)) + GNUNET_CRYPTO_rsa_blind ( + &c_hash->hash, + &coin_bks->rsa_bks, + dk->details.rsa_public_key, + &blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + &blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size)) { GNUNET_break (0); return GNUNET_SYSERR; } return GNUNET_OK; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + { + struct TALER_DenominationCSPublicRPairP blinded_r_pub; + struct GNUNET_CRYPTO_CsBlindingSecret bs[2]; + + blinded_planchet->cipher = TALER_DENOMINATION_CS; + GNUNET_CRYPTO_cs_blinding_secrets_derive (&coin_bks->nonce, + bs); + GNUNET_CRYPTO_cs_calc_blinded_c ( + bs, + alg_values->details.cs_values.r_pub, + &dk->details.cs_public_key, + c_hash, + sizeof(*c_hash), + blinded_planchet->details.cs_blinded_planchet.c, + blinded_r_pub.r_pub); + return GNUNET_OK; + } default: GNUNET_break (0); return GNUNET_SYSERR; @@ -292,7 +373,18 @@ TALER_denom_pub_verify (const struct TALER_DenominationPublicKey *denom_pub, return GNUNET_NO; } return GNUNET_YES; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + if (GNUNET_OK != + GNUNET_CRYPTO_cs_verify (&denom_sig->details.cs_signature, + &denom_pub->details.cs_public_key, + &c_hash->hash, + sizeof(struct GNUNET_HashCode))) + { + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Coin signature is invalid\n"); + return GNUNET_NO; + } + return GNUNET_YES; default: GNUNET_assert (0); } @@ -314,7 +406,8 @@ TALER_denom_pub_free (struct TALER_DenominationPublicKey *denom_pub) } denom_pub->cipher = TALER_DENOMINATION_INVALID; return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -336,7 +429,8 @@ TALER_denom_priv_free (struct TALER_DenominationPrivateKey *denom_priv) } denom_priv->cipher = TALER_DENOMINATION_INVALID; return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -358,7 +452,8 @@ TALER_denom_sig_free (struct TALER_DenominationSignature *denom_sig) } denom_sig->cipher = TALER_DENOMINATION_INVALID; return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -382,20 +477,14 @@ TALER_blinded_denom_sig_free ( } denom_sig->cipher = TALER_DENOMINATION_INVALID; return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } } -/** - * Make a (deep) copy of the given @a denom_src to - * @a denom_dst. - * - * @param[out] denom_dst target to copy to - * @param denom_str public key to copy - */ void TALER_denom_pub_deep_copy (struct TALER_DenominationPublicKey *denom_dst, const struct TALER_DenominationPublicKey *denom_src) @@ -408,7 +497,8 @@ TALER_denom_pub_deep_copy (struct TALER_DenominationPublicKey *denom_dst, = GNUNET_CRYPTO_rsa_public_key_dup ( denom_src->details.rsa_public_key); return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -429,7 +519,8 @@ TALER_denom_sig_deep_copy (struct TALER_DenominationSignature *denom_dst, = GNUNET_CRYPTO_rsa_signature_dup ( denom_src->details.rsa_signature); return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -451,7 +542,8 @@ TALER_blinded_denom_sig_deep_copy ( = GNUNET_CRYPTO_rsa_signature_dup ( denom_src->details.blinded_rsa_signature); return; - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return; default: GNUNET_assert (0); } @@ -473,7 +565,9 @@ TALER_denom_pub_cmp (const struct TALER_DenominationPublicKey *denom1, case TALER_DENOMINATION_RSA: return GNUNET_CRYPTO_rsa_public_key_cmp (denom1->details.rsa_public_key, denom2->details.rsa_public_key); - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return GNUNET_memcmp (&denom1->details.cs_public_key, + &denom2->details.cs_public_key); default: GNUNET_assert (0); } @@ -494,7 +588,38 @@ TALER_denom_sig_cmp (const struct TALER_DenominationSignature *sig1, case TALER_DENOMINATION_RSA: return GNUNET_CRYPTO_rsa_signature_cmp (sig1->details.rsa_signature, sig2->details.rsa_signature); - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return GNUNET_memcmp (&sig1->details.cs_signature, + &sig2->details.cs_signature); + default: + GNUNET_assert (0); + } + return -2; +} + + +int +TALER_blinded_planchet_cmp ( + const struct TALER_BlindedPlanchet *bp1, + const struct TALER_BlindedPlanchet *bp2) +{ + if (bp1->cipher != bp2->cipher) + return (bp1->cipher > bp2->cipher) ? 1 : -1; + switch (bp1->cipher) + { + case TALER_DENOMINATION_INVALID: + return 0; + case TALER_DENOMINATION_RSA: + if (bp1->details.rsa_blinded_planchet.blinded_msg_size != + bp2->details.rsa_blinded_planchet.blinded_msg_size) + return (bp1->details.rsa_blinded_planchet.blinded_msg_size > + bp2->details.rsa_blinded_planchet.blinded_msg_size) ? 1 : -1; + return memcmp (bp1->details.rsa_blinded_planchet.blinded_msg, + bp2->details.rsa_blinded_planchet.blinded_msg, + bp1->details.rsa_blinded_planchet.blinded_msg_size); + case TALER_DENOMINATION_CS: + return GNUNET_memcmp (&bp1->details.cs_blinded_planchet, + &bp2->details.cs_blinded_planchet); default: GNUNET_assert (0); } @@ -516,7 +641,9 @@ TALER_blinded_denom_sig_cmp ( case TALER_DENOMINATION_RSA: return GNUNET_CRYPTO_rsa_signature_cmp (sig1->details.blinded_rsa_signature, sig2->details.blinded_rsa_signature); - // TODO: add case for Clause-Schnorr + case TALER_DENOMINATION_CS: + return GNUNET_memcmp (&sig1->details.blinded_cs_answer, + &sig2->details.blinded_cs_answer); default: GNUNET_assert (0); } @@ -524,4 +651,218 @@ TALER_blinded_denom_sig_cmp ( } +void +TALER_blinded_planchet_hash (const struct TALER_BlindedPlanchet *bp, + struct GNUNET_HashContext *hash_context) +{ + uint32_t cipher = htonl (bp->cipher); + + GNUNET_CRYPTO_hash_context_read (hash_context, + &cipher, + sizeof (cipher)); + switch (bp->cipher) + { + case TALER_DENOMINATION_INVALID: + break; + case TALER_DENOMINATION_RSA: + GNUNET_CRYPTO_hash_context_read ( + hash_context, + bp->details.rsa_blinded_planchet.blinded_msg, + bp->details.rsa_blinded_planchet.blinded_msg_size); + break; + case TALER_DENOMINATION_CS: + GNUNET_CRYPTO_hash_context_read ( + hash_context, + &bp->details.cs_blinded_planchet, + sizeof (bp->details.cs_blinded_planchet)); + break; + default: + GNUNET_assert (0); + break; + } +} + + +void +TALER_planchet_blinding_secret_create ( + const struct TALER_PlanchetMasterSecretP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + union TALER_DenominationBlindingKeyP *bks) +{ + switch (alg_values->cipher) + { + case TALER_DENOMINATION_INVALID: + GNUNET_break (0); + return; + case TALER_DENOMINATION_RSA: + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (&bks->rsa_bks, + sizeof (bks->rsa_bks), + "bks", + strlen ("bks"), + ps, + sizeof(*ps), + NULL, + 0)); + return; + case TALER_DENOMINATION_CS: + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (&bks->nonce, + sizeof (bks->nonce), + "bseed", + strlen ("bseed"), + ps, + sizeof(*ps), + &alg_values->details.cs_values, + sizeof(alg_values->details.cs_values), + NULL, + 0)); + return; + default: + GNUNET_break (0); + } +} + + +void +TALER_planchet_setup_coin_priv ( + const struct TALER_PlanchetMasterSecretP *ps, + const struct TALER_ExchangeWithdrawValues *alg_values, + struct TALER_CoinSpendPrivateKeyP *coin_priv) +{ + switch (alg_values->cipher) + { + case TALER_DENOMINATION_RSA: + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (coin_priv, + sizeof (*coin_priv), + "coin", + strlen ("coin"), + ps, + sizeof(*ps), + NULL, + 0)); + break; + case TALER_DENOMINATION_CS: + GNUNET_assert (GNUNET_YES == + GNUNET_CRYPTO_kdf (coin_priv, + sizeof (*coin_priv), + "coin", + strlen ("coin"), + ps, + sizeof(*ps), + &alg_values->details.cs_values, + sizeof(alg_values->details.cs_values), + NULL, + 0)); + break; + default: + GNUNET_break (0); + return; + } + coin_priv->eddsa_priv.d[0] &= 248; + coin_priv->eddsa_priv.d[31] &= 127; + coin_priv->eddsa_priv.d[31] |= 64; +} + + +void +TALER_blinded_planchet_free (struct TALER_BlindedPlanchet *blinded_planchet) +{ + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + GNUNET_free (blinded_planchet->details.rsa_blinded_planchet.blinded_msg); + break; + case TALER_DENOMINATION_CS: + memset (blinded_planchet, + 0, + sizeof (*blinded_planchet)); + /* nothing to do for CS */ + break; + default: + GNUNET_break (0); + } +} + + +enum GNUNET_GenericReturnValue +TALER_coin_ev_hash (const struct TALER_BlindedPlanchet *blinded_planchet, + const struct TALER_DenominationHash *denom_hash, + struct TALER_BlindedCoinHash *bch) +{ + struct GNUNET_HashContext *hash_context; + + hash_context = GNUNET_CRYPTO_hash_context_start (); + GNUNET_CRYPTO_hash_context_read (hash_context, + denom_hash, + sizeof(*denom_hash)); + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + GNUNET_CRYPTO_hash_context_read ( + hash_context, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size); + break; + case TALER_DENOMINATION_CS: + // FIXME: c-values MUST NOT be included in idempotency check + // during withdraw (or recoup), but right now they are!!! + GNUNET_CRYPTO_hash_context_read ( + hash_context, + &blinded_planchet->details.cs_blinded_planchet.c[0], + sizeof (struct GNUNET_CRYPTO_CsC) * 2); + GNUNET_CRYPTO_hash_context_read ( + hash_context, + &blinded_planchet->details.cs_blinded_planchet.nonce, + sizeof (struct TALER_CsNonce)); + break; + default: + GNUNET_break (0); + GNUNET_CRYPTO_hash_context_abort (hash_context); + return GNUNET_SYSERR; + } + GNUNET_CRYPTO_hash_context_finish (hash_context, + &bch->hash); + return GNUNET_OK; +} + + +enum GNUNET_GenericReturnValue +TALER_withdraw_request_hash ( + const struct TALER_BlindedPlanchet *blinded_planchet, + const struct TALER_DenominationHash *denom_hash, + struct TALER_WithdrawIdentificationHash *wih) +{ + struct GNUNET_HashContext *hash_context; + + hash_context = GNUNET_CRYPTO_hash_context_start (); + GNUNET_CRYPTO_hash_context_read (hash_context, + denom_hash, + sizeof(*denom_hash)); + switch (blinded_planchet->cipher) + { + case TALER_DENOMINATION_RSA: + GNUNET_CRYPTO_hash_context_read ( + hash_context, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg, + blinded_planchet->details.rsa_blinded_planchet.blinded_msg_size); + break; + case TALER_DENOMINATION_CS: + GNUNET_CRYPTO_hash_context_read ( + hash_context, + &blinded_planchet->details.cs_blinded_planchet.nonce, + sizeof (struct TALER_CsNonce)); + break; + default: + GNUNET_break (0); + GNUNET_CRYPTO_hash_context_abort (hash_context); + return GNUNET_SYSERR; + } + GNUNET_CRYPTO_hash_context_finish (hash_context, + &wih->hash); + return GNUNET_OK; +} + + /* end of denom.c */ diff --git a/src/util/exchange_signatures.c b/src/util/exchange_signatures.c index b923c29de..c0c775dc0 100644 --- a/src/util/exchange_signatures.c +++ b/src/util/exchange_signatures.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2021 Taler Systems SA + Copyright (C) 2021, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -66,4 +66,26 @@ TALER_exchange_deposit_confirm_verify ( } +enum GNUNET_GenericReturnValue +TALER_exchange_melt_confirmation_verify ( + const struct TALER_RefreshCommitmentP *rc, + uint32_t noreveal_index, + const struct TALER_ExchangePublicKeyP *exchange_pub, + const struct TALER_ExchangeSignatureP *exchange_sig) +{ + struct TALER_RefreshMeltConfirmationPS confirm = { + .purpose.purpose = htonl (TALER_SIGNATURE_EXCHANGE_CONFIRM_MELT), + .purpose.size = htonl (sizeof (confirm)), + .rc = *rc, + .noreveal_index = htonl (noreveal_index) + }; + + return + GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_EXCHANGE_CONFIRM_MELT, + &confirm, + &exchange_sig->eddsa_signature, + &exchange_pub->eddsa_pub); +} + + /* end of exchange_signatures.c */ diff --git a/src/util/secmod_signatures.c b/src/util/secmod_signatures.c index 9cb15bcf5..8e629ebbc 100644 --- a/src/util/secmod_signatures.c +++ b/src/util/secmod_signatures.c @@ -81,7 +81,7 @@ TALER_exchange_secmod_rsa_sign ( struct TALER_DenominationKeyAnnouncementPS dka = { .purpose.purpose = htonl (TALER_SIGNATURE_SM_RSA_DENOMINATION_KEY), .purpose.size = htonl (sizeof (dka)), - .h_rsa = *h_rsa, + .h_denom.hash = h_rsa->hash, .anchor_time = GNUNET_TIME_timestamp_hton (start_sign), .duration_withdraw = GNUNET_TIME_relative_hton (duration) }; @@ -108,7 +108,7 @@ TALER_exchange_secmod_rsa_verify ( struct TALER_DenominationKeyAnnouncementPS dka = { .purpose.purpose = htonl (TALER_SIGNATURE_SM_RSA_DENOMINATION_KEY), .purpose.size = htonl (sizeof (dka)), - .h_rsa = *h_rsa, + .h_denom.hash = h_rsa->hash, .anchor_time = GNUNET_TIME_timestamp_hton (start_sign), .duration_withdraw = GNUNET_TIME_relative_hton (duration) }; @@ -124,4 +124,59 @@ TALER_exchange_secmod_rsa_verify ( } +void +TALER_exchange_secmod_cs_sign ( + const struct TALER_CsPubHashP *h_cs, + const char *section_name, + struct GNUNET_TIME_Timestamp start_sign, + struct GNUNET_TIME_Relative duration, + const struct TALER_SecurityModulePrivateKeyP *secm_priv, + struct TALER_SecurityModuleSignatureP *secm_sig) +{ + struct TALER_DenominationKeyAnnouncementPS dka = { + .purpose.purpose = htonl (TALER_SIGNATURE_SM_CS_DENOMINATION_KEY), + .purpose.size = htonl (sizeof (dka)), + .h_denom.hash = h_cs->hash, + .anchor_time = GNUNET_TIME_timestamp_hton (start_sign), + .duration_withdraw = GNUNET_TIME_relative_hton (duration) + }; + + GNUNET_CRYPTO_hash (section_name, + strlen (section_name) + 1, + &dka.h_section_name); + GNUNET_CRYPTO_eddsa_sign (&secm_priv->eddsa_priv, + &dka, + &secm_sig->eddsa_signature); + +} + + +enum GNUNET_GenericReturnValue +TALER_exchange_secmod_cs_verify ( + const struct TALER_CsPubHashP *h_cs, + const char *section_name, + struct GNUNET_TIME_Timestamp start_sign, + struct GNUNET_TIME_Relative duration, + const struct TALER_SecurityModulePublicKeyP *secm_pub, + const struct TALER_SecurityModuleSignatureP *secm_sig) +{ + struct TALER_DenominationKeyAnnouncementPS dka = { + .purpose.purpose = htonl (TALER_SIGNATURE_SM_CS_DENOMINATION_KEY), + .purpose.size = htonl (sizeof (dka)), + .h_denom.hash = h_cs->hash, + .anchor_time = GNUNET_TIME_timestamp_hton (start_sign), + .duration_withdraw = GNUNET_TIME_relative_hton (duration) + }; + + GNUNET_CRYPTO_hash (section_name, + strlen (section_name) + 1, + &dka.h_section_name); + return + GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_SM_CS_DENOMINATION_KEY, + &dka, + &secm_sig->eddsa_signature, + &secm_pub->eddsa_pub); +} + + /* end of secmod_signatures.c */ diff --git a/src/util/taler-exchange-secmod-cs.c b/src/util/taler-exchange-secmod-cs.c new file mode 100644 index 000000000..6e4e163b2 --- /dev/null +++ b/src/util/taler-exchange-secmod-cs.c @@ -0,0 +1,1615 @@ +/* + This file is part of TALER + Copyright (C) 2014-2021 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see +*/ +/** + * @file util/taler-exchange-secmod-cs.c + * @brief Standalone process to perform private key CS operations + * @author Christian Grothoff + * + * Key design points: + * - EVERY thread of the exchange will have its own pair of connections to the + * crypto helpers. This way, every thread will also have its own /keys state + * and avoid the need to synchronize on those. + * - auditor signatures and master signatures are to be kept in the exchange DB, + * and merged with the public keys of the helper by the exchange HTTPD! + * - the main loop of the helper is SINGLE-THREADED, but there are + * threads for crypto-workers which do the signing in parallel, one per client. + * - thread-safety: signing happens in parallel, thus when REMOVING private keys, + * we must ensure that all signers are done before we fully free() the + * private key. This is done by reference counting (as work is always + * assigned and collected by the main thread). + */ +#include "platform.h" +#include "taler_util.h" +#include "taler-exchange-secmod-cs.h" +#include +#include +#include +#include "taler_error_codes.h" +#include "taler_signatures.h" +#include "secmod_common.h" +#include + + +/** + * Information we keep per denomination. + */ +struct Denomination; + + +/** + * One particular denomination key. + */ +struct DenominationKey +{ + + /** + * Kept in a DLL of the respective denomination. Sorted by anchor time. + */ + struct DenominationKey *next; + + /** + * Kept in a DLL of the respective denomination. Sorted by anchor time. + */ + struct DenominationKey *prev; + + /** + * Denomination this key belongs to. + */ + struct Denomination *denom; + + /** + * Name of the file this key is stored under. + */ + char *filename; + + /** + * The private key of the denomination. + */ + struct GNUNET_CRYPTO_CsPrivateKey denom_priv; + + /** + * The public key of the denomination. + */ + struct GNUNET_CRYPTO_CsPublicKey denom_pub; + + /** + * Message to transmit to clients to introduce this public key. + */ + struct TALER_CRYPTO_CsKeyAvailableNotification *an; + + /** + * Hash of this denomination's public key. + */ + struct TALER_CsPubHashP h_cs; + + /** + * Time at which this key is supposed to become valid. + */ + struct GNUNET_TIME_Timestamp anchor; + + /** + * Generation when this key was created or revoked. + */ + uint64_t key_gen; + + /** + * Reference counter. Counts the number of threads that are + * using this key at this time. + */ + unsigned int rc; + + /** + * Flag set to true if this key has been purged and the memory + * must be freed as soon as @e rc hits zero. + */ + bool purge; + +}; + + +struct Denomination +{ + + /** + * Kept in a DLL. Sorted by #denomination_action_time(). + */ + struct Denomination *next; + + /** + * Kept in a DLL. Sorted by #denomination_action_time(). + */ + struct Denomination *prev; + + /** + * Head of DLL of actual keys of this denomination. + */ + struct DenominationKey *keys_head; + + /** + * Tail of DLL of actual keys of this denomination. + */ + struct DenominationKey *keys_tail; + + /** + * How long can coins be withdrawn (generated)? Should be small + * enough to limit how many coins will be signed into existence with + * the same key, but large enough to still provide a reasonable + * anonymity set. + */ + struct GNUNET_TIME_Relative duration_withdraw; + + /** + * What is the configuration section of this denomination type? Also used + * for the directory name where the denomination keys are stored. + */ + char *section; + +}; + + +/** + * Return value from main(). + */ +static int global_ret; + +/** + * Time when the key update is executed. + * Either the actual current time, or a pretended time. + */ +static struct GNUNET_TIME_Timestamp now; + +/** + * The time for the key update, as passed by the user + * on the command line. + */ +static struct GNUNET_TIME_Timestamp now_tmp; + +/** + * Where do we store the keys? + */ +static char *keydir; + +/** + * How much should coin creation (@e duration_withdraw) duration overlap + * with the next denomination? Basically, the starting time of two + * denominations is always @e duration_withdraw - #overlap_duration apart. + */ +static struct GNUNET_TIME_Relative overlap_duration; + +/** + * How long into the future do we pre-generate keys? + */ +static struct GNUNET_TIME_Relative lookahead_sign; + +/** + * All of our denominations, in a DLL. Sorted? + */ +static struct Denomination *denom_head; + +/** + * All of our denominations, in a DLL. Sorted? + */ +static struct Denomination *denom_tail; + +/** + * Map of hashes of public (CS) keys to `struct DenominationKey *` + * with the respective private keys. + */ +static struct GNUNET_CONTAINER_MultiHashMap *keys; + +/** + * Task run to generate new keys. + */ +static struct GNUNET_SCHEDULER_Task *keygen_task; + +/** + * Lock for the keys queue. + */ +static pthread_mutex_t keys_lock; + +/** + * Current key generation. + */ +static uint64_t key_gen; + + +/** + * Generate the announcement message for @a dk. + * + * @param[in,out] dk denomination key to generate the announcement for + */ +static void +generate_response (struct DenominationKey *dk) +{ + struct Denomination *denom = dk->denom; + size_t nlen = strlen (denom->section) + 1; + struct TALER_CRYPTO_CsKeyAvailableNotification *an; + void *p; + size_t tlen; + + GNUNET_assert (sizeof(dk->denom_pub) < UINT16_MAX); + GNUNET_assert (nlen < UINT16_MAX); + tlen = nlen + sizeof (*an); + GNUNET_assert (tlen < UINT16_MAX); + an = GNUNET_malloc (tlen); + an->header.size = htons ((uint16_t) tlen); + an->header.type = htons (TALER_HELPER_CS_MT_AVAIL); + an->section_name_len = htons ((uint16_t) nlen); + an->anchor_time = GNUNET_TIME_timestamp_hton (dk->anchor); + an->duration_withdraw = GNUNET_TIME_relative_hton (denom->duration_withdraw); + an->denom_pub = dk->denom_pub; + TALER_exchange_secmod_cs_sign (&dk->h_cs, + denom->section, + dk->anchor, + denom->duration_withdraw, + &TES_smpriv, + &an->secm_sig); + an->secm_pub = TES_smpub; + p = (void *) &an[1]; + memcpy (p, + denom->section, + nlen); + dk->an = an; +} + + +/** + * Handle @a client request @a sr to create signature. Create the + * signature using the respective key and return the result to + * the client. + * + * @param client the client making the request + * @param sr the request details + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +handle_sign_request (struct TES_Client *client, + const struct TALER_CRYPTO_CsSignRequest *sr) +{ + struct DenominationKey *dk; + struct GNUNET_CRYPTO_CsRSecret r[2]; + struct TALER_BlindedDenominationCsSignAnswer cs_answer; + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); + + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + dk = GNUNET_CONTAINER_multihashmap_get (keys, + &sr->h_cs.hash); + if (NULL == dk) + { + struct TALER_CRYPTO_SignFailure sf = { + .header.size = htons (sizeof (sr)), + .header.type = htons (TALER_HELPER_CS_MT_RES_SIGN_FAILURE), + .ec = htonl (TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN) + }; + + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Signing request failed, denomination key %s unknown\n", + GNUNET_h2s (&sr->h_cs.hash)); + return TES_transmit (client->csock, + &sf.header); + } + if (GNUNET_TIME_absolute_is_future (dk->anchor.abs_time)) + { + /* it is too early */ + struct TALER_CRYPTO_SignFailure sf = { + .header.size = htons (sizeof (sr)), + .header.type = htons (TALER_HELPER_CS_MT_RES_SIGN_FAILURE), + .ec = htonl (TALER_EC_EXCHANGE_DENOMINATION_HELPER_TOO_EARLY) + }; + + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Signing request failed, denomination key %s is not yet valid\n", + GNUNET_h2s (&sr->h_cs.hash)); + return TES_transmit (client->csock, + &sf.header); + } + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received request to sign over bytes with key %s\n", + GNUNET_h2s (&sr->h_cs.hash)); + GNUNET_assert (dk->rc < UINT_MAX); + dk->rc++; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_CRYPTO_cs_r_derive (&sr->planchet.nonce.nonce, + &dk->denom_priv, + r); + cs_answer.b = GNUNET_CRYPTO_cs_sign_derive (&dk->denom_priv, + r, + sr->planchet.c, + &sr->planchet.nonce.nonce, + &cs_answer.s_scalar); + + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + GNUNET_assert (dk->rc > 0); + dk->rc--; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + // if (NULL == cs_answer) + // { + // struct TALER_CRYPTO_SignFailure sf = { + // .header.size = htons (sizeof (sf)), + // .header.type = htons (TALER_HELPER_CS_MT_RES_SIGN_FAILURE), + // .ec = htonl (TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE) + // }; + + // GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + // "Signing request failed, worker failed to produce signature\n"); + // return TES_transmit (client->csock, + // &sf.header); + // } + + { + struct TALER_CRYPTO_SignResponse *sr; + size_t tsize; + enum GNUNET_GenericReturnValue ret; + + tsize = sizeof (*sr) + sizeof(cs_answer); + GNUNET_assert (tsize < UINT16_MAX); + sr = GNUNET_malloc (tsize); + sr->header.size = htons (tsize); + sr->header.type = htons (TALER_HELPER_CS_MT_RES_SIGNATURE); + sr->cs_answer = cs_answer; + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Sending CS signature after %s\n", + GNUNET_TIME_relative2s ( + GNUNET_TIME_absolute_get_duration (now), + GNUNET_YES)); + ret = TES_transmit (client->csock, + &sr->header); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Sent CS signature after %s\n", + GNUNET_TIME_relative2s ( + GNUNET_TIME_absolute_get_duration (now), + GNUNET_YES)); + GNUNET_free (sr); + return ret; + } +} + + +/** + * Initialize key material for denomination key @a dk (also on disk). + * + * @param[in,out] dk denomination key to compute key material for + * @param position where in the DLL will the @a dk go + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +setup_key (struct DenominationKey *dk, + struct DenominationKey *position) +{ + struct Denomination *denom = dk->denom; + struct GNUNET_CRYPTO_CsPrivateKey priv; + struct GNUNET_CRYPTO_CsPublicKey pub; + + GNUNET_CRYPTO_cs_private_key_generate (&priv); + GNUNET_CRYPTO_cs_private_key_get_public (&priv, + &pub); + TALER_cs_pub_hash (&pub, + &dk->h_cs); + GNUNET_asprintf (&dk->filename, + "%s/%s/%llu", + keydir, + denom->section, + (unsigned long long) (dk->anchor.abs_time.abs_value_us + / GNUNET_TIME_UNIT_SECONDS.rel_value_us)); + if (GNUNET_OK != + GNUNET_DISK_fn_write (dk->filename, + &priv, + sizeof(priv), + GNUNET_DISK_PERM_USER_READ)) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, + "write", + dk->filename); + return GNUNET_SYSERR; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Setup fresh private key %s at %s in `%s' (generation #%llu)\n", + GNUNET_h2s (&dk->h_cs.hash), + GNUNET_TIME_timestamp2s (dk->anchor), + dk->filename, + (unsigned long long) key_gen); + dk->denom_priv = priv; + dk->denom_pub = pub; + dk->key_gen = key_gen; + generate_response (dk); + if (GNUNET_OK != + GNUNET_CONTAINER_multihashmap_put ( + keys, + &dk->h_cs.hash, + dk, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Duplicate private key created! Terminating.\n"); + GNUNET_free (dk->filename); + GNUNET_free (dk->an); + GNUNET_free (dk); + return GNUNET_SYSERR; + } + GNUNET_CONTAINER_DLL_insert_after (denom->keys_head, + denom->keys_tail, + position, + dk); + return GNUNET_OK; +} + + +/** + * The withdraw period of a key @a dk has expired. Purge it. + * + * @param[in] dk expired denomination key to purge + */ +static void +purge_key (struct DenominationKey *dk) +{ + if (dk->purge) + return; + if (0 != unlink (dk->filename)) + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, + "unlink", + dk->filename); + GNUNET_free (dk->filename); + dk->purge = true; + dk->key_gen = key_gen; +} + + +/** + * A @a client informs us that a key has been revoked. + * Check if the key is still in use, and if so replace (!) + * it with a fresh key. + * + * @param client the client making the request + * @param rr the revocation request + */ +static enum GNUNET_GenericReturnValue +handle_revoke_request (struct TES_Client *client, + const struct TALER_CRYPTO_CsRevokeRequest *rr) +{ + struct DenominationKey *dk; + struct DenominationKey *ndk; + struct Denomination *denom; + + (void) client; + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + dk = GNUNET_CONTAINER_multihashmap_get (keys, + &rr->h_cs.hash); + if (NULL == dk) + { + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Revocation request ignored, denomination key %s unknown\n", + GNUNET_h2s (&rr->h_cs.hash)); + return GNUNET_OK; + } + if (dk->purge) + { + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Revocation request ignored, denomination key %s already revoked\n", + GNUNET_h2s (&rr->h_cs.hash)); + return GNUNET_OK; + } + + key_gen++; + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Revoking key %s, bumping generation to %llu\n", + GNUNET_h2s (&rr->h_cs.hash), + (unsigned long long) key_gen); + purge_key (dk); + + /* Setup replacement key */ + denom = dk->denom; + ndk = GNUNET_new (struct DenominationKey); + ndk->denom = denom; + ndk->anchor = dk->anchor; + if (GNUNET_OK != + setup_key (ndk, + dk)) + { + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_break (0); + GNUNET_SCHEDULER_shutdown (); + global_ret = EXIT_FAILURE; + return GNUNET_SYSERR; + } + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + TES_wake_clients (); + return GNUNET_OK; +} + + +/** + * Handle @a client request @a rdr to create signature. Create the + * signature using the respective key and return the result to + * the client. + * + * @param client the client making the request + * @param rdr the request details + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +handle_r_derive_request (struct TES_Client *client, + const struct TALER_CRYPTO_CsRDeriveRequest *rdr) +{ + struct DenominationKey *dk; + struct TALER_DenominationCSPrivateRPairP r_priv; + struct TALER_DenominationCSPublicRPairP r_pub; + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); + + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + dk = GNUNET_CONTAINER_multihashmap_get (keys, + &rdr->h_cs.hash); + if (NULL == dk) + { + struct TALER_CRYPTO_RDeriveFailure rdf = { + .header.size = htons (sizeof (rdr)), + .header.type = htons (TALER_HELPER_CS_MT_RES_RDERIVE_FAILURE), + .ec = htonl (TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN) + }; + + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "R Derive request failed, denomination key %s unknown\n", + GNUNET_h2s (&rdr->h_cs.hash)); + return TES_transmit (client->csock, + &rdf.header); + } + if (GNUNET_TIME_absolute_is_future (dk->anchor.abs_time)) + { + /* it is too early */ + struct TALER_CRYPTO_RDeriveFailure rdf = { + .header.size = htons (sizeof (rdr)), + .header.type = htons (TALER_HELPER_CS_MT_RES_RDERIVE_FAILURE), + .ec = htonl (TALER_EC_EXCHANGE_DENOMINATION_HELPER_TOO_EARLY) + }; + + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "R Derive request failed, denomination key %s is not yet valid\n", + GNUNET_h2s (&rdr->h_cs.hash)); + return TES_transmit (client->csock, + &rdf.header); + } + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received request to derive R with key %s\n", + GNUNET_h2s (&rdr->h_cs.hash)); + GNUNET_assert (dk->rc < UINT_MAX); + dk->rc++; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_CRYPTO_cs_r_derive (&rdr->nonce.nonce, + &dk->denom_priv, + r_priv.r); + GNUNET_CRYPTO_cs_r_get_public (&r_priv.r[0], &r_pub.r_pub[0]); + GNUNET_CRYPTO_cs_r_get_public (&r_priv.r[1], &r_pub.r_pub[1]); + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + GNUNET_assert (dk->rc > 0); + dk->rc--; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + + { + struct TALER_CRYPTO_RDeriveResponse rdr = { + .header.size = htons (sizeof (struct TALER_CRYPTO_RDeriveResponse)), + .header.type = htons (TALER_HELPER_CS_MT_RES_RDERIVE), + .r_pub = r_pub + }; + enum GNUNET_GenericReturnValue ret; + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Sending CS Derived R after %s\n", + GNUNET_TIME_relative2s ( + GNUNET_TIME_absolute_get_duration (now), + GNUNET_YES)); + ret = TES_transmit (client->csock, + &rdr.header); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Sent CS Derived R after %s\n", + GNUNET_TIME_relative2s ( + GNUNET_TIME_absolute_get_duration (now), + GNUNET_YES)); + return ret; + } +} + + +/** + * Handle @a hdr message received from @a client. + * + * @param client the client that received the message + * @param hdr message that was received + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +cs_work_dispatch (struct TES_Client *client, + const struct GNUNET_MessageHeader *hdr) +{ + uint16_t msize = ntohs (hdr->size); + + switch (ntohs (hdr->type)) + { + case TALER_HELPER_CS_MT_REQ_SIGN: + if (msize < sizeof (struct TALER_CRYPTO_CsSignRequest)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return handle_sign_request ( + client, + (const struct TALER_CRYPTO_CsSignRequest *) hdr); + case TALER_HELPER_CS_MT_REQ_REVOKE: + if (msize != sizeof (struct TALER_CRYPTO_CsRevokeRequest)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return handle_revoke_request ( + client, + (const struct TALER_CRYPTO_CsRevokeRequest *) hdr); + case TALER_HELPER_CS_MT_REQ_RDERIVE: + if (msize != sizeof (struct TALER_CRYPTO_CsRDeriveRequest)) + { + GNUNET_break_op (0); + return GNUNET_SYSERR; + } + return handle_r_derive_request (client, + (const struct + TALER_CRYPTO_CsRDeriveRequest *) hdr); + default: + GNUNET_break_op (0); + return GNUNET_SYSERR; + } +} + + +/** + * Send our initial key set to @a client together with the + * "sync" terminator. + * + * @param client the client to inform + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +cs_client_init (struct TES_Client *client) +{ + size_t obs = 0; + char *buf; + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Initializing new client %p\n", + client); + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + for (struct Denomination *denom = denom_head; + NULL != denom; + denom = denom->next) + { + for (struct DenominationKey *dk = denom->keys_head; + NULL != dk; + dk = dk->next) + { + obs += ntohs (dk->an->header.size); + } + } + buf = GNUNET_malloc (obs); + obs = 0; + for (struct Denomination *denom = denom_head; + NULL != denom; + denom = denom->next) + { + for (struct DenominationKey *dk = denom->keys_head; + NULL != dk; + dk = dk->next) + { + memcpy (&buf[obs], + dk->an, + ntohs (dk->an->header.size)); + obs += ntohs (dk->an->header.size); + } + } + client->key_gen = key_gen; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + if (GNUNET_OK != + TES_transmit_raw (client->csock, + obs, + buf)) + { + GNUNET_free (buf); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Client %p must have disconnected\n", + client); + return GNUNET_SYSERR; + } + GNUNET_free (buf); + { + struct GNUNET_MessageHeader synced = { + .type = htons (TALER_HELPER_CS_SYNCED), + .size = htons (sizeof (synced)) + }; + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Sending CS SYNCED message to %p\n", + client); + if (GNUNET_OK != + TES_transmit (client->csock, + &synced)) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + } + return GNUNET_OK; +} + + +/** + * Notify @a client about all changes to the keys since + * the last generation known to the @a client. + * + * @param client the client to notify + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +cs_update_client_keys (struct TES_Client *client) +{ + size_t obs = 0; + char *buf; + enum GNUNET_GenericReturnValue ret; + + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + for (struct Denomination *denom = denom_head; + NULL != denom; + denom = denom->next) + { + for (struct DenominationKey *key = denom->keys_head; + NULL != key; + key = key->next) + { + if (key->key_gen <= client->key_gen) + continue; + if (key->purge) + obs += sizeof (struct TALER_CRYPTO_CsKeyPurgeNotification); + else + obs += ntohs (key->an->header.size); + } + } + if (0 == obs) + { + /* nothing to do */ + client->key_gen = key_gen; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + return GNUNET_OK; + } + buf = GNUNET_malloc (obs); + obs = 0; + for (struct Denomination *denom = denom_head; + NULL != denom; + denom = denom->next) + { + for (struct DenominationKey *key = denom->keys_head; + NULL != key; + key = key->next) + { + if (key->key_gen <= client->key_gen) + continue; + if (key->purge) + { + struct TALER_CRYPTO_CsKeyPurgeNotification pn = { + .header.type = htons (TALER_HELPER_CS_MT_PURGE), + .header.size = htons (sizeof (pn)), + .h_cs = key->h_cs + }; + + memcpy (&buf[obs], + &pn, + sizeof (pn)); + obs += sizeof (pn); + } + else + { + memcpy (&buf[obs], + key->an, + ntohs (key->an->header.size)); + obs += ntohs (key->an->header.size); + } + } + } + client->key_gen = key_gen; + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + ret = TES_transmit_raw (client->csock, + obs, + buf); + GNUNET_free (buf); + return ret; +} + + +/** + * Create a new denomination key (we do not have enough). + * + * @param denom denomination key to create + * @param now current time to use (to get many keys to use the exact same time) + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +create_key (struct Denomination *denom, + struct GNUNET_TIME_Timestamp now) +{ + struct DenominationKey *dk; + struct GNUNET_TIME_Timestamp anchor; + + anchor = now; + if (NULL != denom->keys_tail) + { + struct GNUNET_TIME_Absolute abs; + + abs = GNUNET_TIME_absolute_add (denom->keys_tail->anchor.abs_time, + GNUNET_TIME_relative_subtract ( + denom->duration_withdraw, + overlap_duration)); + if (GNUNET_TIME_absolute_cmp (now.abs_time, <, abs)) + anchor = GNUNET_TIME_absolute_to_timestamp (abs); + } + dk = GNUNET_new (struct DenominationKey); + dk->denom = denom; + dk->anchor = anchor; + if (GNUNET_OK != + setup_key (dk, + denom->keys_tail)) + { + GNUNET_break (0); + GNUNET_free (dk); + GNUNET_SCHEDULER_shutdown (); + global_ret = EXIT_FAILURE; + return GNUNET_SYSERR; + } + return GNUNET_OK; +} + + +/** + * At what time does this denomination require its next action? + * Basically, the minimum of the withdraw expiration time of the + * oldest denomination key, and the withdraw expiration time of + * the newest denomination key minus the #lookahead_sign time. + * + * @param denom denomination to compute action time for + */ +static struct GNUNET_TIME_Absolute +denomination_action_time (const struct Denomination *denom) +{ + struct DenominationKey *head = denom->keys_head; + struct DenominationKey *tail = denom->keys_tail; + struct GNUNET_TIME_Absolute tt; + + if (NULL == head) + return GNUNET_TIME_UNIT_ZERO_ABS; + tt = GNUNET_TIME_absolute_subtract ( + GNUNET_TIME_absolute_subtract ( + GNUNET_TIME_absolute_add (tail->anchor.abs_time, + denom->duration_withdraw), + lookahead_sign), + overlap_duration); + if (head->rc > 0) + return tt; /* head expiration does not count due to rc > 0 */ + return GNUNET_TIME_absolute_min ( + GNUNET_TIME_absolute_add (head->anchor.abs_time, + denom->duration_withdraw), + tt); +} + + +/** + * Create new keys and expire ancient keys of the given denomination @a denom. + * Removes the @a denom from the #denom_head DLL and re-insert its at the + * correct location sorted by next maintenance activity. + * + * @param[in,out] denom denomination to update material for + * @param now current time to use (to get many keys to use the exact same time) + * @param[in,out] wake set to true if we should wake the clients + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +update_keys (struct Denomination *denom, + struct GNUNET_TIME_Timestamp now, + bool *wake) +{ + /* create new denomination keys */ + if (NULL != denom->keys_tail) + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Updating keys of denomination `%s', last key %s valid for another %s\n", + denom->section, + GNUNET_h2s (&denom->keys_tail->h_cs.hash), + GNUNET_TIME_relative2s ( + GNUNET_TIME_absolute_get_remaining ( + GNUNET_TIME_absolute_subtract ( + GNUNET_TIME_absolute_add ( + denom->keys_tail->anchor.abs_time, + denom->duration_withdraw), + overlap_duration)), + GNUNET_YES)); + while ( (NULL == denom->keys_tail) || + GNUNET_TIME_absolute_is_past ( + GNUNET_TIME_absolute_subtract ( + GNUNET_TIME_absolute_subtract ( + GNUNET_TIME_absolute_add (denom->keys_tail->anchor.abs_time, + denom->duration_withdraw), + lookahead_sign), + overlap_duration)) ) + { + if (! *wake) + { + key_gen++; + *wake = true; + } + if (GNUNET_OK != + create_key (denom, + now)) + { + GNUNET_break (0); + global_ret = EXIT_FAILURE; + GNUNET_SCHEDULER_shutdown (); + return GNUNET_SYSERR; + } + } + /* remove expired denomination keys */ + while ( (NULL != denom->keys_head) && + GNUNET_TIME_absolute_is_past + (GNUNET_TIME_absolute_add (denom->keys_head->anchor.abs_time, + denom->duration_withdraw)) ) + { + struct DenominationKey *key = denom->keys_head; + struct DenominationKey *nxt = key->next; + + if (0 != key->rc) + break; /* later */ + GNUNET_CONTAINER_DLL_remove (denom->keys_head, + denom->keys_tail, + key); + GNUNET_assert (GNUNET_OK == + GNUNET_CONTAINER_multihashmap_remove ( + keys, + &key->h_cs.hash, + key)); + if ( (! key->purge) && + (0 != unlink (key->filename)) ) + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, + "unlink", + key->filename); + GNUNET_free (key->filename); + GNUNET_free (key->an); + GNUNET_free (key); + key = nxt; + } + + /* Update position of 'denom' in #denom_head DLL: sort by action time */ + { + struct Denomination *before; + struct GNUNET_TIME_Absolute at; + + at = denomination_action_time (denom); + GNUNET_CONTAINER_DLL_remove (denom_head, + denom_tail, + denom); + before = NULL; + for (struct Denomination *pos = denom_head; + NULL != pos; + pos = pos->next) + { + if (GNUNET_TIME_absolute_cmp (denomination_action_time (pos), >=, at)) + break; + before = pos; + } + GNUNET_CONTAINER_DLL_insert_after (denom_head, + denom_tail, + before, + denom); + } + return GNUNET_OK; +} + + +/** + * Task run periodically to expire keys and/or generate fresh ones. + * + * @param cls NULL + */ +static void +update_denominations (void *cls) +{ + struct Denomination *denom; + struct GNUNET_TIME_Absolute now; + struct GNUNET_TIME_Timestamp t; + bool wake = false; + + (void) cls; + keygen_task = NULL; + now = GNUNET_TIME_absolute_get (); + t = GNUNET_TIME_absolute_to_timestamp (now); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Updating denominations ...\n"); + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + do { + denom = denom_head; + if (GNUNET_OK != + update_keys (denom, + t, + &wake)) + return; + } while (denom != denom_head); + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + "Updating denominations finished ...\n"); + if (wake) + TES_wake_clients (); + keygen_task = GNUNET_SCHEDULER_add_at (denomination_action_time (denom), + &update_denominations, + NULL); +} + + +/** + * Parse private key of denomination @a denom in @a buf. + * + * @param[out] denom denomination of the key + * @param filename name of the file we are parsing, for logging + * @param priv key material + */ +static void +parse_key (struct Denomination *denom, + const char *filename, + const struct GNUNET_CRYPTO_CsPrivateKey *priv) +{ + char *anchor_s; + char dummy; + unsigned long long anchor_ll; + struct GNUNET_TIME_Timestamp anchor; + + anchor_s = strrchr (filename, + '/'); + if (NULL == anchor_s) + { + /* File in a directory without '/' in the name, this makes no sense. */ + GNUNET_break (0); + return; + } + anchor_s++; + if (1 != sscanf (anchor_s, + "%llu%c", + &anchor_ll, + &dummy)) + { + /* Filenames in KEYDIR must ONLY be the anchor time in seconds! */ + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Filename `%s' invalid for key file, skipping\n", + filename); + return; + } + anchor.abs_time.abs_value_us + = anchor_ll * GNUNET_TIME_UNIT_SECONDS.rel_value_us; + if (anchor_ll != anchor.abs_time.abs_value_us + / GNUNET_TIME_UNIT_SECONDS.rel_value_us) + { + /* Integer overflow. Bad, invalid filename. */ + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "Filename `%s' invalid for key file, skipping\n", + filename); + return; + } + { + struct GNUNET_CRYPTO_CsPublicKey pub; + struct DenominationKey *dk; + struct DenominationKey *before; + + GNUNET_CRYPTO_cs_private_key_get_public (priv, + &pub); + dk = GNUNET_new (struct DenominationKey); + dk->denom_priv = *priv; + dk->denom = denom; + dk->anchor = anchor; + dk->filename = GNUNET_strdup (filename); + TALER_cs_pub_hash (&pub, + &dk->h_cs); + dk->denom_pub = pub; + generate_response (dk); + if (GNUNET_OK != + GNUNET_CONTAINER_multihashmap_put ( + keys, + &dk->h_cs.hash, + dk, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Duplicate private key %s detected in file `%s'. Skipping.\n", + GNUNET_h2s (&dk->h_cs.hash), + filename); + GNUNET_free (dk->an); + GNUNET_free (dk); + return; + } + before = NULL; + for (struct DenominationKey *pos = denom->keys_head; + NULL != pos; + pos = pos->next) + { + if (GNUNET_TIME_timestamp_cmp (pos->anchor, >, anchor)) + break; + before = pos; + } + GNUNET_CONTAINER_DLL_insert_after (denom->keys_head, + denom->keys_tail, + before, + dk); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Imported key %s from `%s'\n", + GNUNET_h2s (&dk->h_cs.hash), + filename); + } +} + + +/** + * Import a private key from @a filename for the denomination + * given in @a cls. + * + * @param[in,out] cls a `struct Denomiantion` + * @param filename name of a file in the directory + * @return #GNUNET_OK (always, continue to iterate) + */ +static enum GNUNET_GenericReturnValue +import_key (void *cls, + const char *filename) +{ + struct Denomination *denom = cls; + struct GNUNET_DISK_FileHandle *fh; + struct GNUNET_DISK_MapHandle *map; + void *ptr; + int fd; + struct stat sbuf; + + { + struct stat lsbuf; + + if (0 != lstat (filename, + &lsbuf)) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "lstat", + filename); + return GNUNET_OK; + } + if (! S_ISREG (lsbuf.st_mode)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "File `%s' is not a regular file, which is not allowed for private keys!\n", + filename); + return GNUNET_OK; + } + } + + fd = open (filename, + O_CLOEXEC); + if (-1 == fd) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "open", + filename); + GNUNET_break (0 == close (fd)); + return GNUNET_OK; + } + if (0 != fstat (fd, + &sbuf)) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "stat", + filename); + return GNUNET_OK; + } + if (! S_ISREG (sbuf.st_mode)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "File `%s' is not a regular file, which is not allowed for private keys!\n", + filename); + GNUNET_break (0 == close (fd)); + return GNUNET_OK; + } + if (0 != (sbuf.st_mode & (S_IWUSR | S_IRWXG | S_IRWXO))) + { + /* permission are NOT tight, try to patch them up! */ + if (0 != + fchmod (fd, + S_IRUSR)) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "fchmod", + filename); + /* refuse to use key if file has wrong permissions */ + GNUNET_break (0 == close (fd)); + return GNUNET_OK; + } + } + fh = GNUNET_DISK_get_handle_from_int_fd (fd); + if (NULL == fh) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "open", + filename); + GNUNET_break (0 == close (fd)); + return GNUNET_OK; + } + if (sbuf.st_size != sizeof(struct GNUNET_CRYPTO_CsPrivateKey)) + { + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "File `%s' too big to be a private key\n", + filename); + GNUNET_DISK_file_close (fh); + return GNUNET_OK; + } + ptr = GNUNET_DISK_file_map (fh, + &map, + GNUNET_DISK_MAP_TYPE_READ, + (size_t) sbuf.st_size); + if (NULL == ptr) + { + GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, + "mmap", + filename); + GNUNET_DISK_file_close (fh); + return GNUNET_OK; + } + parse_key (denom, + filename, + (const struct GNUNET_CRYPTO_CsPrivateKey *) ptr); + GNUNET_DISK_file_unmap (map); + GNUNET_DISK_file_close (fh); + return GNUNET_OK; +} + + +/** + * Parse configuration for denomination type parameters. Also determines + * our anchor by looking at the existing denominations of the same type. + * + * @param cfg configuration to use + * @param ct section in the configuration file giving the denomination type parameters + * @param[out] denom set to the denomination parameters from the configuration + * @return #GNUNET_OK on success, #GNUNET_SYSERR if the configuration is invalid + */ +static enum GNUNET_GenericReturnValue +parse_denomination_cfg (const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *ct, + struct Denomination *denom) +{ + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_time (cfg, + ct, + "DURATION_WITHDRAW", + &denom->duration_withdraw)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + ct, + "DURATION_WITHDRAW"); + return GNUNET_SYSERR; + } + if (GNUNET_TIME_relative_cmp (overlap_duration, + >=, + denom->duration_withdraw)) + { + GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "OVERLAP_DURATION", + "Value given must be smaller than value for DURATION_WITHDRAW!"); + return GNUNET_SYSERR; + } + denom->section = GNUNET_strdup (ct); + return GNUNET_OK; +} + + +/** + * Closure for #load_denominations. + */ +struct LoadContext +{ + + /** + * Configuration to use. + */ + const struct GNUNET_CONFIGURATION_Handle *cfg; + + /** + * Current time to use. + */ + struct GNUNET_TIME_Timestamp t; + + /** + * Status, to be set to #GNUNET_SYSERR on failure + */ + enum GNUNET_GenericReturnValue ret; +}; + + +/** + * Generate new denomination signing keys for the denomination type of the given @a + * denomination_alias. + * + * @param cls a `struct LoadContext`, with 'ret' to be set to #GNUNET_SYSERR on failure + * @param denomination_alias name of the denomination's section in the configuration + */ +static void +load_denominations (void *cls, + const char *denomination_alias) +{ + struct LoadContext *ctx = cls; + struct Denomination *denom; + bool wake = true; + char *cipher; + + if ( (0 != strncasecmp (denomination_alias, + "coin_", + strlen ("coin_"))) && + (0 != strncasecmp (denomination_alias, + "coin-", + strlen ("coin-"))) ) + return; /* not a denomination type definition */ + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string (ctx->cfg, + denomination_alias, + "CIPHER", + &cipher)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + denomination_alias, + "CIPHER"); + return; + } + if (0 != strcmp (cipher, "CS")) + { + GNUNET_free (cipher); + return; /* Ignore denominations of other types than CS*/ + } + GNUNET_free (cipher); + + denom = GNUNET_new (struct Denomination); + if (GNUNET_OK != + parse_denomination_cfg (ctx->cfg, + denomination_alias, + denom)) + { + ctx->ret = GNUNET_SYSERR; + GNUNET_free (denom); + return; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Loading keys for denomination %s\n", + denom->section); + { + char *dname; + + GNUNET_asprintf (&dname, + "%s/%s", + keydir, + denom->section); + GNUNET_break (GNUNET_OK == + GNUNET_DISK_directory_create (dname)); + GNUNET_DISK_directory_scan (dname, + &import_key, + denom); + GNUNET_free (dname); + } + GNUNET_CONTAINER_DLL_insert (denom_head, + denom_tail, + denom); + update_keys (denom, + ctx->t, + &wake); +} + + +/** + * Load the various duration values from @a cfg + * + * @param cfg configuration to use + * @return #GNUNET_OK on success + */ +static enum GNUNET_GenericReturnValue +load_durations (const struct GNUNET_CONFIGURATION_Handle *cfg) +{ + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_time (cfg, + "taler-exchange-secmod-cs", + "OVERLAP_DURATION", + &overlap_duration)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "OVERLAP_DURATION"); + return GNUNET_SYSERR; + } + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_time (cfg, + "taler-exchange-secmod-cs", + "LOOKAHEAD_SIGN", + &lookahead_sign)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "LOOKAHEAD_SIGN"); + return GNUNET_SYSERR; + } + return GNUNET_OK; +} + + +/** + * Function run on shutdown. Stops the various jobs (nicely). + * + * @param cls NULL + */ +static void +do_shutdown (void *cls) +{ + (void) cls; + TES_listen_stop (); + if (NULL != keygen_task) + { + GNUNET_SCHEDULER_cancel (keygen_task); + keygen_task = NULL; + } +} + + +/** + * Main function that will be run under the GNUnet scheduler. + * + * @param cls closure + * @param args remaining command-line arguments + * @param cfgfile name of the configuration file used (for saving, can be NULL!) + * @param cfg configuration + */ +static void +run (void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) +{ + static struct TES_Callbacks cb = { + .dispatch = &cs_work_dispatch, + .updater = &cs_update_client_keys, + .init = &cs_client_init + }; + + (void) cls; + (void) args; + (void) cfgfile; + if (GNUNET_TIME_timestamp_cmp (now, !=, now_tmp)) + { + /* The user gave "--now", use it! */ + now = now_tmp; + } + else + { + /* get current time again, we may be timetraveling! */ + now = GNUNET_TIME_timestamp_get (); + } + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_filename (cfg, + "taler-exchange-secmod-cs", + "KEY_DIR", + &keydir)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + "taler-exchange-secmod-cs", + "KEY_DIR"); + global_ret = EXIT_NOTCONFIGURED; + return; + } + if (GNUNET_OK != + load_durations (cfg)) + { + global_ret = EXIT_NOTCONFIGURED; + return; + } + global_ret = TES_listen_start (cfg, + "taler-exchange-secmod-cs", + &cb); + if (0 != global_ret) + return; + GNUNET_SCHEDULER_add_shutdown (&do_shutdown, + NULL); + /* Load denominations */ + keys = GNUNET_CONTAINER_multihashmap_create (65536, + GNUNET_YES); + { + struct LoadContext lc = { + .cfg = cfg, + .ret = GNUNET_OK, + .t = now + }; + + GNUNET_assert (0 == pthread_mutex_lock (&keys_lock)); + GNUNET_CONFIGURATION_iterate_sections (cfg, + &load_denominations, + &lc); + GNUNET_assert (0 == pthread_mutex_unlock (&keys_lock)); + if (GNUNET_OK != lc.ret) + { + global_ret = EXIT_FAILURE; + GNUNET_SCHEDULER_shutdown (); + return; + } + } + if (NULL == denom_head) + { + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "No CS denominations configured\n"); + TES_wake_clients (); + return; + } + /* start job to keep keys up-to-date; MUST be run before the #listen_task, + hence with priority. */ + keygen_task = GNUNET_SCHEDULER_add_with_priority ( + GNUNET_SCHEDULER_PRIORITY_URGENT, + &update_denominations, + NULL); +} + + +/** + * The entry point. + * + * @param argc number of arguments in @a argv + * @param argv command-line arguments + * @return 0 on normal termination + */ +int +main (int argc, + char **argv) +{ + struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_timetravel ('T', + "timetravel"), + GNUNET_GETOPT_option_timestamp ('t', + "time", + "TIMESTAMP", + "pretend it is a different time for the update", + &now_tmp), + GNUNET_GETOPT_OPTION_END + }; + enum GNUNET_GenericReturnValue ret; + + /* Restrict permissions for the key files that we create. */ + (void) umask (S_IWGRP | S_IROTH | S_IWOTH | S_IXOTH); + + /* force linker to link against libtalerutil; if we do + not do this, the linker may "optimize" libtalerutil + away and skip #TALER_OS_init(), which we do need */ + TALER_OS_init (); + now_tmp = now = GNUNET_TIME_timestamp_get (); + ret = GNUNET_PROGRAM_run (argc, argv, + "taler-exchange-secmod-cs", + "Handle private CS key operations for a Taler exchange", + options, + &run, + NULL); + if (GNUNET_NO == ret) + return EXIT_SUCCESS; + if (GNUNET_SYSERR == ret) + return EXIT_INVALIDARGUMENT; + return global_ret; +} diff --git a/src/util/taler-exchange-secmod-cs.conf b/src/util/taler-exchange-secmod-cs.conf new file mode 100644 index 000000000..5085eab79 --- /dev/null +++ b/src/util/taler-exchange-secmod-cs.conf @@ -0,0 +1,23 @@ +[taler-exchange-secmod-cs] + +# How long should generated coins overlap in their validity +# periods. Should be long enough to avoid problems with +# wallets picking one key and then due to network latency +# another key being valid. The DURATION_WITHDRAW period +# must be longer than this value. +OVERLAP_DURATION = 5 m + +# Where do we store the generated private keys. +KEY_DIR = ${TALER_DATA_HOME}/exchange-secmod-cs/keys + +# Where does the helper listen for requests? +UNIXPATH = $TALER_RUNTIME_DIR/exchange-secmod-cs/server.sock + +# Directory for clients. +CLIENT_DIR = $TALER_RUNTIME_DIR/exchange-secmod-cs/clients + +# Where should the security module store its own private key? +SM_PRIV_KEY = ${TALER_DATA_HOME}/exchange-secmod-cs/secmod-private-key + +# For how long into the future do we pre-generate keys? +LOOKAHEAD_SIGN = 1 year diff --git a/src/util/taler-exchange-secmod-cs.h b/src/util/taler-exchange-secmod-cs.h new file mode 100644 index 000000000..c090e5cd1 --- /dev/null +++ b/src/util/taler-exchange-secmod-cs.h @@ -0,0 +1,270 @@ +/* + This file is part of TALER + Copyright (C) 2020 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see +*/ +/** + * @file util/taler-exchange-secmod-cs.h + * @brief IPC messages for the CS crypto helper. + * @author Christian Grothoff + * @author Gian Demarmels + * @author Lucien Heuzeveldt + */ +#ifndef TALER_EXCHANGE_SECMOD_CS_H +#define TALER_EXCHANGE_SECMOD_CS_H + +#define TALER_HELPER_CS_MT_PURGE 1 +#define TALER_HELPER_CS_MT_AVAIL 2 + +#define TALER_HELPER_CS_MT_REQ_INIT 4 +#define TALER_HELPER_CS_MT_REQ_SIGN 5 +#define TALER_HELPER_CS_MT_REQ_REVOKE 6 +#define TALER_HELPER_CS_MT_REQ_RDERIVE 7 + +#define TALER_HELPER_CS_MT_RES_SIGNATURE 8 +#define TALER_HELPER_CS_MT_RES_SIGN_FAILURE 9 +#define TALER_HELPER_CS_MT_RES_RDERIVE 10 +#define TALER_HELPER_CS_MT_RES_RDERIVE_FAILURE 11 + +#define TALER_HELPER_CS_SYNCED 12 + +GNUNET_NETWORK_STRUCT_BEGIN + + +/** + * Message sent if a key is available. + */ +struct TALER_CRYPTO_CsKeyAvailableNotification +{ + /** + * Type is #TALER_HELPER_CS_MT_AVAIL + */ + struct GNUNET_MessageHeader header; + + /** + * Number of bytes of the section name. + */ + uint32_t section_name_len; + + /** + * When does the key become available? + */ + struct GNUNET_TIME_TimestampNBO anchor_time; + + /** + * How long is the key available after @e anchor_time? + */ + struct GNUNET_TIME_RelativeNBO duration_withdraw; + + /** + * Public key used to generate the @e sicm_sig. + */ + struct TALER_SecurityModulePublicKeyP secm_pub; + + /** + * Signature affirming the announcement, of + * purpose #TALER_SIGNATURE_SM_CS_DENOMINATION_KEY. + */ + struct TALER_SecurityModuleSignatureP secm_sig; + + /** + * Denomination Public key + */ + struct GNUNET_CRYPTO_CsPublicKey denom_pub; + + /* followed by @e section_name bytes of the configuration section name + of the denomination of this key */ + +}; + + +/** + * Message sent if a key was purged. + */ +struct TALER_CRYPTO_CsKeyPurgeNotification +{ + /** + * Type is #TALER_HELPER_CS_MT_PURGE. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * Hash of the public key of the purged CS key. + */ + struct TALER_CsPubHashP h_cs; + +}; + + +/** + * Message sent if a signature is requested. + */ +struct TALER_CRYPTO_CsSignRequest +{ + /** + * Type is #TALER_HELPER_CS_MT_REQ_SIGN. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * Hash of the public key of the CS key to use for the signature. + */ + struct TALER_CsPubHashP h_cs; + + /** + * Planchet containing message to sign + * and nonce to derive R from + */ + struct TALER_BlindedCsPlanchet planchet; + +}; + +/** + * Message sent if a signature is requested. + */ +struct TALER_CRYPTO_CsRDeriveRequest +{ + /** + * Type is #TALER_HELPER_CS_MT_REQ_RDERIVE. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * Hash of the public key of the CS key to use for the derivation. + */ + struct TALER_CsPubHashP h_cs; + + /** + * Withdraw nonce to derive R from + */ + struct TALER_CsNonce nonce; +}; + +/** + * Message sent if a key was revoked. + */ +struct TALER_CRYPTO_CsRevokeRequest +{ + /** + * Type is #TALER_HELPER_CS_MT_REQ_REVOKE. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * Hash of the public key of the revoked CS key. + */ + struct TALER_CsPubHashP h_cs; + +}; + + +/** + * Message sent if a signature was successfully computed. + */ +struct TALER_CRYPTO_SignResponse +{ + /** + * Type is #TALER_HELPER_CS_MT_RES_SIGNATURE. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * Contains the blindided s and the chosen b + */ + struct TALER_BlindedDenominationCsSignAnswer cs_answer; +}; + +/** + * Message sent if a R is successfully derived + */ +struct TALER_CRYPTO_RDeriveResponse +{ + /** + * Type is #TALER_HELPER_CS_MT_RES_RDERIVE. + */ + struct GNUNET_MessageHeader header; + + /** + * For now, always zero. + */ + uint32_t reserved; + + /** + * derived R + */ + struct TALER_DenominationCSPublicRPairP r_pub; +}; + + +/** + * Message sent if signing failed. + */ +struct TALER_CRYPTO_SignFailure +{ + /** + * Type is #TALER_HELPER_CS_MT_RES_SIGN_FAILURE. + */ + struct GNUNET_MessageHeader header; + + /** + * If available, Taler error code. In NBO. + */ + uint32_t ec; + +}; + +/** + * Message sent if derivation failed. + */ +struct TALER_CRYPTO_RDeriveFailure +{ + /** + * Type is #TALER_HELPER_CS_MT_RES_RDERIVE_FAILURE. + */ + struct GNUNET_MessageHeader header; + + /** + * If available, Taler error code. In NBO. + */ + uint32_t ec; + +}; +GNUNET_NETWORK_STRUCT_END + + +#endif diff --git a/src/util/taler-exchange-secmod-rsa.c b/src/util/taler-exchange-secmod-rsa.c index 433879299..402e43196 100644 --- a/src/util/taler-exchange-secmod-rsa.c +++ b/src/util/taler-exchange-secmod-rsa.c @@ -232,7 +232,7 @@ static uint64_t key_gen; /** * Generate the announcement message for @a dk. * - * @param[in,out] denomination key to generate the announcement for + * @param[in,out] dk denomination key to generate the announcement for */ static void generate_response (struct DenominationKey *dk) @@ -1340,6 +1340,7 @@ load_denominations (void *cls, struct LoadContext *ctx = cls; struct Denomination *denom; bool wake = true; + char *cipher; if ( (0 != strncasecmp (denomination_alias, "coin_", @@ -1348,6 +1349,23 @@ load_denominations (void *cls, "coin-", strlen ("coin-"))) ) return; /* not a denomination type definition */ + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string (ctx->cfg, + denomination_alias, + "CIPHER", + &cipher)) + { + GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, + denomination_alias, + "CIPHER"); + return; + } + if (0 != strcmp (cipher, "RSA")) + { + GNUNET_free (cipher); + return; /* Ignore denominations of other types than CS */ + } + GNUNET_free (cipher); denom = GNUNET_new (struct Denomination); if (GNUNET_OK != parse_denomination_cfg (ctx->cfg, @@ -1519,10 +1537,9 @@ run (void *cls, } if (NULL == denom_head) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No denominations configured\n"); - global_ret = EXIT_NOTCONFIGURED; - GNUNET_SCHEDULER_shutdown (); + GNUNET_log (GNUNET_ERROR_TYPE_WARNING, + "No RSA denominations configured\n"); + TES_wake_clients (); return; } /* start job to keep keys up-to-date; MUST be run before the #listen_task, diff --git a/src/util/taler-exchange-secmod-rsa.h b/src/util/taler-exchange-secmod-rsa.h index 61fa58811..625ff87d9 100644 --- a/src/util/taler-exchange-secmod-rsa.h +++ b/src/util/taler-exchange-secmod-rsa.h @@ -73,7 +73,7 @@ struct TALER_CRYPTO_RsaKeyAvailableNotification /** * Signature affirming the announcement, of - * purpose #TALER_SIGNATURE_SM_DENOMINATION_KEY. + * purpose #TALER_SIGNATURE_SM_RSA_DENOMINATION_KEY. */ struct TALER_SecurityModuleSignatureP secm_sig; diff --git a/src/util/test_crypto.c b/src/util/test_crypto.c index c1f5d4e2a..cda17d9b6 100644 --- a/src/util/test_crypto.c +++ b/src/util/test_crypto.c @@ -1,6 +1,6 @@ /* This file is part of TALER - (C) 2015, 2020, 2021 Taler Systems SA + (C) 2015, 2020-2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -38,8 +38,14 @@ test_high_level (void) struct TALER_TransferPublicKeyP trans_pub; struct TALER_TransferSecretP secret; struct TALER_TransferSecretP secret2; - struct TALER_PlanchetSecretsP fc1; - struct TALER_PlanchetSecretsP fc2; + union TALER_DenominationBlindingKeyP bks1; + union TALER_DenominationBlindingKeyP bks2; + struct TALER_CoinSpendPrivateKeyP coin_priv1; + struct TALER_CoinSpendPrivateKeyP coin_priv2; + struct TALER_PlanchetMasterSecretP ps1; + struct TALER_PlanchetMasterSecretP ps2; + struct TALER_ExchangeWithdrawValues alg1; + struct TALER_ExchangeWithdrawValues alg2; GNUNET_CRYPTO_eddsa_key_create (&coin_priv.eddsa_priv); GNUNET_CRYPTO_eddsa_key_get_public (&coin_priv.eddsa_priv, @@ -62,15 +68,35 @@ test_high_level (void) GNUNET_assert (0 == GNUNET_memcmp (&secret, &secret2)); - TALER_planchet_setup_refresh (&secret, - 0, - &fc1); - TALER_planchet_setup_refresh (&secret, - 1, - &fc2); + TALER_transfer_secret_to_planchet_secret (&secret, + 0, + &ps1); + alg1.cipher = TALER_DENOMINATION_RSA; + TALER_planchet_setup_coin_priv (&ps1, + &alg1, + &coin_priv1); + TALER_planchet_blinding_secret_create (&ps1, + &alg1, + &bks1); + alg2.cipher = TALER_DENOMINATION_RSA; + TALER_transfer_secret_to_planchet_secret (&secret, + 1, + &ps2); + TALER_planchet_setup_coin_priv (&ps2, + &alg2, + &coin_priv2); + TALER_planchet_blinding_secret_create (&ps2, + &alg2, + &bks2); GNUNET_assert (0 != - GNUNET_memcmp (&fc1, - &fc2)); + GNUNET_memcmp (&ps1, + &ps2)); + GNUNET_assert (0 != + GNUNET_memcmp (&coin_priv1, + &coin_priv2)); + GNUNET_assert (0 != + GNUNET_memcmp (&bks1, + &bks2)); return 0; } @@ -82,39 +108,170 @@ test_high_level (void) * @return 0 on success */ static int -test_planchets (void) +test_planchets_rsa (void) { - struct TALER_PlanchetSecretsP ps; + struct TALER_PlanchetMasterSecretP ps; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; struct TALER_DenominationPrivateKey dk_priv; struct TALER_DenominationPublicKey dk_pub; + struct TALER_ExchangeWithdrawValues alg_values; struct TALER_PlanchetDetail pd; struct TALER_BlindedDenominationSignature blind_sig; struct TALER_FreshCoin coin; struct TALER_CoinPubHash c_hash; + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG, + &ps, + sizeof (ps)); + + GNUNET_assert (GNUNET_SYSERR == + TALER_denom_priv_create (&dk_priv, + &dk_pub, + TALER_DENOMINATION_INVALID)); + + GNUNET_assert (GNUNET_SYSERR == + TALER_denom_priv_create (&dk_priv, + &dk_pub, + 42)); + GNUNET_assert (GNUNET_OK == TALER_denom_priv_create (&dk_priv, &dk_pub, TALER_DENOMINATION_RSA, 1024)); - TALER_planchet_setup_random (&ps); + alg_values.cipher = TALER_DENOMINATION_RSA; + TALER_planchet_setup_coin_priv (&ps, + &alg_values, + &coin_priv); + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); GNUNET_assert (GNUNET_OK == TALER_planchet_prepare (&dk_pub, - &ps, + &alg_values, + &bks, + &coin_priv, NULL, /* no age commitment */ &c_hash, &pd)); GNUNET_assert (GNUNET_OK == TALER_denom_sign_blinded (&blind_sig, &dk_priv, - pd.coin_ev, - pd.coin_ev_size)); + &pd.blinded_planchet)); + TALER_planchet_detail_free (&pd); GNUNET_assert (GNUNET_OK == TALER_planchet_to_coin (&dk_pub, &blind_sig, - &ps, + &bks, + &coin_priv, NULL, /* no age commitment */ &c_hash, + &alg_values, + &coin)); + TALER_blinded_denom_sig_free (&blind_sig); + TALER_denom_sig_free (&coin.sig); + TALER_denom_priv_free (&dk_priv); + TALER_denom_pub_free (&dk_pub); + return 0; +} + + +/** FIXME-oec: Add test for planchets with age commitment hash */ + +/** + * @brief Function for CS signatures to derive public R_0 and R_1 + * + * @param nonce withdraw nonce from a client + * @param denom_priv denomination privkey as long-term secret + * @param r_pub the resulting R_0 and R_1 + * @return enum GNUNET_GenericReturnValue + */ +static enum GNUNET_GenericReturnValue +derive_r_public ( + const struct TALER_CsNonce *nonce, + const struct TALER_DenominationPrivateKey *denom_priv, + struct TALER_DenominationCSPublicRPairP *r_pub) +{ + struct GNUNET_CRYPTO_CsRSecret r[2]; + + if (denom_priv->cipher != TALER_DENOMINATION_CS) + { + GNUNET_break (0); + return GNUNET_SYSERR; + } + GNUNET_CRYPTO_cs_r_derive (&nonce->nonce, + &denom_priv->details.cs_private_key, + r); + GNUNET_CRYPTO_cs_r_get_public (&r[0], + &r_pub->r_pub[0]); + GNUNET_CRYPTO_cs_r_get_public (&r[1], + &r_pub->r_pub[1]); + return GNUNET_OK; +} + + +/** + * Test the basic planchet functionality of creating a fresh planchet with CS denomination + * and extracting the respective signature. + * + * @return 0 on success + */ +static int +test_planchets_cs (void) +{ + struct TALER_PlanchetMasterSecretP ps; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; + struct TALER_DenominationPrivateKey dk_priv; + struct TALER_DenominationPublicKey dk_pub; + struct TALER_PlanchetDetail pd; + struct TALER_CoinPubHash c_hash; + struct TALER_BlindedDenominationSignature blind_sig; + struct TALER_FreshCoin coin; + struct TALER_ExchangeWithdrawValues alg_values; + + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG, + &ps, + sizeof (ps)); + GNUNET_assert (GNUNET_OK == + TALER_denom_priv_create (&dk_priv, + &dk_pub, + TALER_DENOMINATION_CS)); + alg_values.cipher = TALER_DENOMINATION_CS; + TALER_cs_withdraw_nonce_derive ( + &ps, + &pd.blinded_planchet.details.cs_blinded_planchet.nonce); + GNUNET_assert (GNUNET_OK == + derive_r_public ( + &pd.blinded_planchet.details.cs_blinded_planchet.nonce, + &dk_priv, + &alg_values.details.cs_values)); + TALER_planchet_setup_coin_priv (&ps, + &alg_values, + &coin_priv); + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); + GNUNET_assert (GNUNET_OK == + TALER_planchet_prepare (&dk_pub, + &alg_values, + &bks, + &coin_priv, + &c_hash, + &pd)); + GNUNET_assert (GNUNET_OK == + TALER_denom_sign_blinded (&blind_sig, + &dk_priv, + &pd.blinded_planchet)); + TALER_planchet_detail_free (&pd); + GNUNET_assert (GNUNET_OK == + TALER_planchet_to_coin (&dk_pub, + &blind_sig, + &bks, + &coin_priv, + &c_hash, + &alg_values, &coin)); TALER_blinded_denom_sig_free (&blind_sig); TALER_denom_sig_free (&coin.sig); @@ -125,57 +282,18 @@ test_planchets (void) /** - * Test the basic planchet functionality of creating a fresh planchet and - * extracting the respective signature, this time _with_ age commitment. + * Test the basic planchet functionality of creating a fresh planchet + * and extracting the respective signature. + * Calls test_planchets_rsa and test_planchets_cs * * @return 0 on success */ static int -test_planchets_with_age_commitment (void) +test_planchets (void) { - struct TALER_PlanchetSecretsP ps; - struct TALER_AgeCommitmentHash ach; - struct TALER_DenominationPrivateKey dk_priv; - struct TALER_DenominationPublicKey dk_pub; - struct TALER_PlanchetDetail pd; - struct TALER_BlindedDenominationSignature blind_sig; - struct TALER_FreshCoin coin; - struct TALER_CoinPubHash c_hash; - - GNUNET_assert (GNUNET_OK == - TALER_denom_priv_create (&dk_priv, - &dk_pub, - TALER_DENOMINATION_RSA, - 1024)); - TALER_planchet_setup_random (&ps); - GNUNET_CRYPTO_random_block ( - GNUNET_CRYPTO_QUALITY_WEAK, - &ach, - sizeof(struct TALER_AgeCommitmentHash)); - - GNUNET_assert (GNUNET_OK == - TALER_planchet_prepare (&dk_pub, - &ps, - &ach, - &c_hash, - &pd)); - GNUNET_assert (GNUNET_OK == - TALER_denom_sign_blinded (&blind_sig, - &dk_priv, - pd.coin_ev, - pd.coin_ev_size)); - GNUNET_assert (GNUNET_OK == - TALER_planchet_to_coin (&dk_pub, - &blind_sig, - &ps, - &ach, - &c_hash, - &coin)); - TALER_blinded_denom_sig_free (&blind_sig); - TALER_denom_sig_free (&coin.sig); - TALER_denom_priv_free (&dk_priv); - TALER_denom_pub_free (&dk_pub); - return 0; + if (0 != test_planchets_rsa ()) + return -1; + return test_planchets_cs (); } @@ -218,7 +336,7 @@ static int test_merchant_sigs (void) { const char *pt = "payto://x-taler-bank/localhost/Account"; - struct TALER_WireSalt salt; + struct TALER_WireSaltP salt; struct TALER_MerchantPrivateKeyP priv; struct TALER_MerchantPublicKeyP pub; struct TALER_MerchantSignatureP sig; diff --git a/src/util/test_helper_cs.c b/src/util/test_helper_cs.c new file mode 100644 index 000000000..6e5626d95 --- /dev/null +++ b/src/util/test_helper_cs.c @@ -0,0 +1,873 @@ +/* + This file is part of TALER + (C) 2020, 2021 Taler Systems SA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see +*/ +/** + * @file util/test_helper_cs.c + * @brief Tests for CS crypto helper + * @author Christian Grothoff + */ +#include "platform.h" +#include "taler_util.h" + +/** + * Configuration has 1 minute duration and 5 minutes lookahead, but + * we do not get 'revocations' for expired keys. So this must be + * large enough to deal with key rotation during the runtime of + * the benchmark. + */ +#define MAX_KEYS 1024 + +/** + * How many random key revocations should we test? + */ +#define NUM_REVOKES 3 + +/** + * How many iterations of the successful signing test should we run? + */ +#define NUM_SIGN_TESTS 5 + +/** + * How many iterations of the successful signing test should we run + * during the benchmark phase? + */ +#define NUM_SIGN_PERFS 100 + +/** + * How many parallel clients should we use for the parallel + * benchmark? (> 500 may cause problems with the max open FD number limit). + */ +#define NUM_CORES 8 + +/** + * Number of keys currently in #keys. + */ +static unsigned int num_keys; + +/** + * Keys currently managed by the helper. + */ +struct KeyData +{ + /** + * Validity start point. + */ + struct GNUNET_TIME_Timestamp start_time; + + /** + * Key expires for signing at @e start_time plus this value. + */ + struct GNUNET_TIME_Relative validity_duration; + + /** + * Hash of the public key. + */ + struct TALER_CsPubHashP h_cs; + + /** + * Full public key. + */ + struct TALER_DenominationPublicKey denom_pub; + + /** + * Is this key currently valid? + */ + bool valid; + + /** + * Did the test driver revoke this key? + */ + bool revoked; +}; + +/** + * Array of all the keys we got from the helper. + */ +static struct KeyData keys[MAX_KEYS]; + + +/** + * Release memory occupied by #keys. + */ +static void +free_keys (void) +{ + for (unsigned int i = 0; i 0); + num_keys--; + } +} + + +/** + * Function called with information about available keys for signing. Usually + * only called once per key upon connect. Also called again in case a key is + * being revoked, in that case with an @a end_time of zero. Stores the keys + * status in #keys. + * + * @param cls closure, NULL + * @param section_name name of the denomination type in the configuration; + * NULL if the key has been revoked or purged + * @param start_time when does the key become available for signing; + * zero if the key has been revoked or purged + * @param validity_duration how long does the key remain available for signing; + * zero if the key has been revoked or purged + * @param h_cs hash of the @a denom_pub that is available (or was purged) + * @param denom_pub the public key itself, NULL if the key was revoked or purged + * @param sm_pub public key of the security module, NULL if the key was revoked or purged + * @param sm_sig signature from the security module, NULL if the key was revoked or purged + * The signature was already verified against @a sm_pub. + */ +static void +key_cb (void *cls, + const char *section_name, + struct GNUNET_TIME_Timestamp start_time, + struct GNUNET_TIME_Relative validity_duration, + const struct TALER_CsPubHashP *h_cs, + const struct TALER_DenominationPublicKey *denom_pub, + const struct TALER_SecurityModulePublicKeyP *sm_pub, + const struct TALER_SecurityModuleSignatureP *sm_sig) +{ + (void) cls; + (void) sm_pub; + (void) sm_sig; + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Key notification about key %s in `%s'\n", + GNUNET_h2s (&h_cs->hash), + section_name); + if (0 == validity_duration.rel_value_us) + { + bool found = false; + + GNUNET_break (NULL == denom_pub); + GNUNET_break (NULL == section_name); + for (unsigned int i = 0; i 0); + num_keys--; + found = true; + break; + } + if (! found) + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Error: helper announced expiration of unknown key!\n"); + + return; + } + + GNUNET_break (NULL != denom_pub); + for (unsigned int i = 0; i, + GNUNET_TIME_UNIT_SECONDS)) + { + /* key worked too early */ + GNUNET_break (0); + return 4; + } + if (GNUNET_TIME_relative_cmp (GNUNET_TIME_absolute_get_duration ( + keys[i].start_time.abs_time), + >, + keys[i].validity_duration)) + { + /* key worked too later */ + GNUNET_break (0); + return 5; + } + + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received valid R for key %s\n", + GNUNET_h2s (&keys[i].h_cs.hash)); + TALER_planchet_setup_coin_priv (&ps, + &alg_values, + &coin_priv); + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); + GNUNET_assert (GNUNET_OK == + TALER_planchet_prepare (&keys[i].denom_pub, + &alg_values, + &bks, + &coin_priv, + &c_hash, + &pd)); + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Successfully prepared planchet"); + success = true; + break; + case TALER_EC_EXCHANGE_DENOMINATION_HELPER_TOO_EARLY: + /* This 'failure' is expected, we're testing also for the + error handling! */ + if ( (GNUNET_TIME_relative_is_zero ( + GNUNET_TIME_absolute_get_remaining ( + keys[i].start_time.abs_time))) && + (GNUNET_TIME_relative_cmp ( + GNUNET_TIME_absolute_get_duration ( + keys[i].start_time.abs_time), + <, + keys[i].validity_duration)) ) + { + /* key should have worked! */ + GNUNET_break (0); + return 6; + } + break; + default: + /* unexpected error */ + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Unexpected error %d\n", + ec); + return 7; + } + } + if (! success) + { + /* no valid key for signing found, also bad */ + GNUNET_break (0); + return 16; + } + + /* check R derivation does not work if the key is unknown */ + { + struct TALER_CsPubHashP rnd; + struct TALER_CsNonce nonce; + struct TALER_DenominationCSPublicRPairP crp; + + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, + &rnd, + sizeof (rnd)); + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, + &nonce, + sizeof (nonce)); + ec = TALER_CRYPTO_helper_cs_r_derive (dh, + &rnd, + &nonce, + &crp); + if (TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN != ec) + { + GNUNET_break (0); + return 17; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "R derivation with invalid key %s failed as desired\n", + GNUNET_h2s (&rnd.hash)); + } + return 0; +} + + +/** + * Test signing logic. + * + * @param dh handle to the helper + * @return 0 on success + */ +static int +test_signing (struct TALER_CRYPTO_CsDenominationHelper *dh) +{ + struct TALER_BlindedDenominationSignature ds; + enum TALER_ErrorCode ec; + bool success = false; + struct TALER_PlanchetMasterSecretP ps; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; + struct TALER_CoinPubHash c_hash; + struct TALER_ExchangeWithdrawValues alg_values; + + TALER_planchet_master_setup_random (&ps); + for (unsigned int i = 0; i, + GNUNET_TIME_UNIT_SECONDS)) + { + /* key worked too early */ + GNUNET_break (0); + return 4; + } + if (GNUNET_TIME_relative_cmp (GNUNET_TIME_absolute_get_duration ( + keys[i].start_time.abs_time), + >, + keys[i].validity_duration)) + { + /* key worked too later */ + GNUNET_break (0); + return 5; + } + { + struct TALER_FreshCoin coin; + if (GNUNET_OK != + TALER_planchet_to_coin (&keys[i].denom_pub, + &ds, + &bks, + &coin_priv, + &c_hash, + &alg_values, + &coin)) + { + GNUNET_break (0); + return 6; + } + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Received valid signature for key %s\n", + GNUNET_h2s (&keys[i].h_cs.hash)); + success = true; + break; + case TALER_EC_EXCHANGE_DENOMINATION_HELPER_TOO_EARLY: + /* This 'failure' is expected, we're testing also for the + error handling! */ + if ( (GNUNET_TIME_relative_is_zero ( + GNUNET_TIME_absolute_get_remaining ( + keys[i].start_time.abs_time))) && + (GNUNET_TIME_relative_cmp ( + GNUNET_TIME_absolute_get_duration ( + keys[i].start_time.abs_time), + <, + keys[i].validity_duration)) ) + { + /* key should have worked! */ + GNUNET_break (0); + return 6; + } + break; + default: + /* unexpected error */ + GNUNET_log (GNUNET_ERROR_TYPE_ERROR, + "Unexpected error %d\n", + ec); + return 7; + } + } + if (! success) + { + /* no valid key for signing found, also bad */ + GNUNET_break (0); + return 16; + } + + /* check signing does not work if the key is unknown */ + { + struct TALER_PlanchetDetail pd; + struct TALER_CsPubHashP rnd; + + GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, + &rnd, + sizeof (rnd)); + pd.blinded_planchet.cipher = TALER_DENOMINATION_CS; + GNUNET_assert (GNUNET_YES == + TALER_planchet_prepare (&keys[0].denom_pub, + &alg_values, + &bks, + &coin_priv, + &c_hash, + &pd)); + + ec = TALER_CRYPTO_helper_cs_sign (dh, + &rnd, + &pd.blinded_planchet.details. + cs_blinded_planchet, + &ds); + if (TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN != ec) + { + if (TALER_EC_NONE == ec) + TALER_blinded_denom_sig_free (&ds); + GNUNET_break (0); + return 17; + } + GNUNET_log (GNUNET_ERROR_TYPE_INFO, + "Signing with invalid key %s failed as desired\n", + GNUNET_h2s (&rnd.hash)); + } + return 0; +} + + +/** + * Benchmark signing logic. + * + * @param dh handle to the helper + * @return 0 on success + */ +static int +perf_signing (struct TALER_CRYPTO_CsDenominationHelper *dh, + const char *type) +{ + struct TALER_BlindedDenominationSignature ds; + enum TALER_ErrorCode ec; + struct GNUNET_TIME_Relative duration; + struct TALER_PlanchetMasterSecretP ps; + struct TALER_CoinSpendPrivateKeyP coin_priv; + union TALER_DenominationBlindingKeyP bks; + struct TALER_ExchangeWithdrawValues alg_values; + + TALER_planchet_master_setup_random (&ps); + duration = GNUNET_TIME_UNIT_ZERO; + TALER_CRYPTO_helper_cs_poll (dh); + for (unsigned int j = 0; j, + GNUNET_TIME_UNIT_SECONDS)) + continue; + if (GNUNET_TIME_relative_cmp (GNUNET_TIME_absolute_get_duration ( + keys[i].start_time.abs_time), + >, + keys[i].validity_duration)) + continue; + { + struct TALER_CoinPubHash c_hash; + struct TALER_PlanchetDetail pd; + + pd.blinded_planchet.cipher = TALER_DENOMINATION_CS; + TALER_cs_withdraw_nonce_derive (&ps, + &pd.blinded_planchet.details. + cs_blinded_planchet.nonce); + alg_values.cipher = TALER_DENOMINATION_CS; + ec = TALER_CRYPTO_helper_cs_r_derive (dh, + &keys[i].h_cs, + &pd.blinded_planchet. + details. + cs_blinded_planchet.nonce, + &alg_values.details.cs_values); + if (TALER_EC_NONE != ec) + continue; + TALER_planchet_setup_coin_priv (&ps, + &alg_values, + &coin_priv); + TALER_planchet_blinding_secret_create (&ps, + &alg_values, + &bks); + GNUNET_assert (GNUNET_YES == + TALER_planchet_prepare (&keys[i].denom_pub, + &alg_values, + &bks, + &coin_priv, + &c_hash, + &pd)); + /* use this key as long as it works */ + while (1) + { + struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get (); + struct GNUNET_TIME_Relative delay; + + ec = TALER_CRYPTO_helper_cs_sign (dh, + &keys[i].h_cs, + &pd.blinded_planchet.details. + cs_blinded_planchet, + &ds); + if (TALER_EC_NONE != ec) + break; + delay = GNUNET_TIME_absolute_get_duration (start); + duration = GNUNET_TIME_relative_add (duration, + delay); + TALER_blinded_denom_sig_free (&ds); + j++; + if (NUM_SIGN_PERFS <= j) + break; + } + } + } /* for i */ + } /* for j */ + fprintf (stderr, + "%u (%s) signature operations took %s\n", + (unsigned int) NUM_SIGN_PERFS, + type, + GNUNET_STRINGS_relative_time_to_string (duration, + GNUNET_YES)); + return 0; +} + + +/** + * Parallel signing logic. + * + * @param esh handle to the helper + * @return 0 on success + */ +static int +par_signing (struct GNUNET_CONFIGURATION_Handle *cfg) +{ + struct GNUNET_TIME_Absolute start; + struct GNUNET_TIME_Relative duration; + pid_t pids[NUM_CORES]; + struct TALER_CRYPTO_CsDenominationHelper *dh; + + start = GNUNET_TIME_absolute_get (); + for (unsigned int i = 0; i, @@ -453,7 +482,9 @@ perf_signing (struct TALER_CRYPTO_RsaDenominationHelper *dh, GNUNET_assert (GNUNET_YES == TALER_planchet_prepare (&keys[i].denom_pub, - &ps, + &alg_values, + &bks, + &coin_priv, &ach, &c_hash, &pd)); @@ -463,11 +494,14 @@ perf_signing (struct TALER_CRYPTO_RsaDenominationHelper *dh, struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get (); struct GNUNET_TIME_Relative delay; - ds = TALER_CRYPTO_helper_rsa_sign (dh, + ec = TALER_CRYPTO_helper_rsa_sign (dh, &keys[i].h_rsa, - pd.coin_ev, - pd.coin_ev_size, - &ec); + pd.blinded_planchet.details. + rsa_blinded_planchet.blinded_msg, + pd.blinded_planchet.details. + rsa_blinded_planchet. + blinded_msg_size, + &ds); if (TALER_EC_NONE != ec) break; delay = GNUNET_TIME_absolute_get_duration (start); @@ -478,7 +512,7 @@ perf_signing (struct TALER_CRYPTO_RsaDenominationHelper *dh, if (NUM_SIGN_PERFS <= j) break; } - GNUNET_free (pd.coin_ev); + TALER_blinded_planchet_free (&pd.blinded_planchet); } } /* for i */ } /* for j */ diff --git a/src/util/test_helper_rsa.conf b/src/util/test_helper_rsa.conf index 6f445fc56..d50e64d95 100644 --- a/src/util/test_helper_rsa.conf +++ b/src/util/test_helper_rsa.conf @@ -4,6 +4,7 @@ TALER_TEST_HOME = test_helper_rsa_home/ [coin_1] DURATION_WITHDRAW = 1 minute +CIPHER = RSA RSA_KEYSIZE = 2048 [taler-exchange-secmod-rsa] diff --git a/src/util/url.c b/src/util/url.c index 199863448..a76d2f88a 100644 --- a/src/util/url.c +++ b/src/util/url.c @@ -102,12 +102,6 @@ buffer_write_urlencode (struct GNUNET_Buffer *buf, } -/** - * URL-encode a string according to rfc3986. - * - * @param s string to encode - * @returns the urlencoded string, the caller must free it with #GNUNET_free() - */ char * TALER_urlencode (const char *s) { @@ -212,20 +206,6 @@ serialize_arguments (struct GNUNET_Buffer *buf, } -/** - * Make an absolute URL with query parameters. - * - * If a 'value' is given as NULL, both the key and the value are skipped. Note - * that a NULL value does not terminate the list, only a NULL key signals the - * end of the list of arguments. - * - * @param base_url absolute base URL to use - * @param path path of the url - * @param ... NULL-terminated key-value pairs (char *) for query parameters, - * the value will be url-encoded - * @returns the URL (must be freed with #GNUNET_free) or - * NULL if an error occurred. - */ char * TALER_url_join (const char *base_url, const char *path, @@ -282,21 +262,6 @@ TALER_url_join (const char *base_url, } -/** - * Make an absolute URL for the given parameters. - * - * If a 'value' is given as NULL, both the key and the value are skipped. Note - * that a NULL value does not terminate the list, only a NULL key signals the - * end of the list of arguments. - * - * @param proto protocol for the URL (typically https) - * @param host hostname for the URL - * @param prefix prefix for the URL - * @param path path for the URL - * @param args NULL-terminated key-value pairs (char *) for query parameters, - * the value will be url-encoded - * @returns the URL, must be freed with #GNUNET_free - */ char * TALER_url_absolute_raw_va (const char *proto, const char *host, @@ -329,21 +294,6 @@ TALER_url_absolute_raw_va (const char *proto, } -/** - * Make an absolute URL for the given parameters. - * - * If a 'value' is given as NULL, both the key and the value are skipped. Note - * that a NULL value does not terminate the list, only a NULL key signals the - * end of the list of arguments. - * - * @param proto protocol for the URL (typically https) - * @param host hostname for the URL - * @param prefix prefix for the URL - * @param path path for the URL - * @param ... NULL-terminated key-value pairs (char *) for query parameters, - * the value will be url-encoded - * @return the URL, must be freed with #GNUNET_free - */ char * TALER_url_absolute_raw (const char *proto, const char *host, diff --git a/src/util/wallet_signatures.c b/src/util/wallet_signatures.c index 00ec2bc24..aaa796dc7 100644 --- a/src/util/wallet_signatures.c +++ b/src/util/wallet_signatures.c @@ -1,6 +1,6 @@ /* This file is part of TALER - Copyright (C) 2021 Taler Systems SA + Copyright (C) 2021, 2022 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -123,9 +123,7 @@ TALER_wallet_deposit_verify ( void TALER_wallet_link_sign (const struct TALER_DenominationHash *h_denom_pub, const struct TALER_TransferPublicKeyP *transfer_pub, - // FIXME: consider passing hash! - const void *coin_ev, - size_t coin_ev_size, + const struct TALER_BlindedCoinHash *bch, const struct TALER_CoinSpendPrivateKeyP *old_coin_priv, struct TALER_CoinSpendSignatureP *coin_sig) { @@ -133,12 +131,10 @@ TALER_wallet_link_sign (const struct TALER_DenominationHash *h_denom_pub, .purpose.size = htonl (sizeof (ldp)), .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_LINK), .h_denom_pub = *h_denom_pub, - .transfer_pub = *transfer_pub + .transfer_pub = *transfer_pub, + .coin_envelope_hash = *bch }; - GNUNET_CRYPTO_hash (coin_ev, - coin_ev_size, - &ldp.coin_envelope_hash.hash); GNUNET_CRYPTO_eddsa_sign (&old_coin_priv->eddsa_priv, &ldp, &coin_sig->eddsa_signature); @@ -315,4 +311,69 @@ TALER_wallet_melt_verify ( } +void +TALER_wallet_withdraw_sign ( + const struct TALER_DenominationHash *h_denom_pub, + const struct TALER_Amount *amount_with_fee, + const struct TALER_BlindedCoinHash *bch, + const struct TALER_ReservePrivateKeyP *reserve_priv, + struct TALER_ReserveSignatureP *reserve_sig) +{ + struct TALER_WithdrawRequestPS req = { + .purpose.size = htonl (sizeof (req)), + .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW), + .h_denomination_pub = *h_denom_pub, + .h_coin_envelope = *bch + }; + + TALER_amount_hton (&req.amount_with_fee, + amount_with_fee); + GNUNET_CRYPTO_eddsa_sign (&reserve_priv->eddsa_priv, + &req, + &reserve_sig->eddsa_signature); +} + + +enum GNUNET_GenericReturnValue +TALER_wallet_withdraw_verify ( + const struct TALER_DenominationHash *h_denom_pub, + const struct TALER_Amount *amount_with_fee, + const struct TALER_BlindedCoinHash *bch, + const struct TALER_ReservePublicKeyP *reserve_pub, + const struct TALER_ReserveSignatureP *reserve_sig) +{ + struct TALER_WithdrawRequestPS wsrd = { + .purpose.size = htonl (sizeof (wsrd)), + .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW), + .h_denomination_pub = *h_denom_pub, + .h_coin_envelope = *bch + }; + + TALER_amount_hton (&wsrd.amount_with_fee, + amount_with_fee); + return GNUNET_CRYPTO_eddsa_verify ( + TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW, + &wsrd, + &reserve_sig->eddsa_signature, + &reserve_pub->eddsa_pub); +} + + +void +TALER_wallet_account_setup_sign ( + const struct TALER_ReservePrivateKeyP *reserve_priv, + struct TALER_ReserveSignatureP *reserve_sig) +{ + struct GNUNET_CRYPTO_EccSignaturePurpose purpose = { + .size = htonl (sizeof (purpose)), + .purpose = htonl (TALER_SIGNATURE_WALLET_ACCOUNT_SETUP) + }; + + GNUNET_assert (GNUNET_OK == + GNUNET_CRYPTO_eddsa_sign_ (&reserve_priv->eddsa_priv, + &purpose, + &reserve_sig->eddsa_signature)); +} + + /* end of wallet_signatures.c */