+ /*
+ * Delete the key if we already have it.
+ *
+ * TODO: Can we optimize this perhaps? Possibly when other data is
+ * involved as well? I suspect this is easiest and doesn't make a lot
+ * of difference though - the largest chunk of data is the keydata and
+ * it definitely needs updated.
+ */
+ if (update) {
+ deadlock = (db4_delete_key(keyid, true) == -1);
+ }
+
+ /*
+ * Convert the key to a flat set of binary data.
+ */
+ if (!deadlock) {
+ next = publickey->next;
+ publickey->next = NULL;
+ flatten_publickey(publickey, &packets, &list_end);
+ publickey->next = next;
+
+ storebuf.offset = 0;
+ storebuf.size = 8192;
+ storebuf.buffer = malloc(8192);
+
+ write_openpgp_stream(buffer_putchar, &storebuf, packets);
+
+ /*
+ * Now we have the key data store it in the DB; the keyid is
+ * the key.
+ */
+ memset(&key, 0, sizeof(key));
+ memset(&data, 0, sizeof(data));
+ key.data = &keyid;
+ key.size = sizeof(keyid);
+ data.size = storebuf.offset;
+ data.data = storebuf.buffer;
+
+ ret = keydb(keyid)->put(keydb(keyid),
+ txn,
+ &key,
+ &data,
+ 0); /* flags*/
+ if (ret != 0) {
+ logthing(LOGTHING_ERROR,
+ "Problem storing key: %s",
+ db_strerror(ret));
+ if (ret == DB_LOCK_DEADLOCK) {
+ deadlock = true;
+ }
+ }
+
+ free(storebuf.buffer);
+ storebuf.buffer = NULL;
+ storebuf.size = 0;
+ storebuf.offset = 0;
+
+ free_packet_list(packets);
+ packets = NULL;
+ }